簡體   English   中英

在Angular 6的初始組件之間共享服務API數據

[英]Share service API data between initial components in Angular 6

我正在嘗試使用帶有類別的導航欄和也使用這些類別的home組件。 我不想調用我的API兩次,我將在其他地方使用相同的category變量。 我嘗試執行以下操作:

數據服務

該服務從api網址獲取數據並返回可訂閱的對象。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  api_url: string = "https://apiurlhere";
  categories: Object;

  constructor(private http: HttpClient) { }

  getCategories(){
    return this.http.get(this.api_url+'/categorylisting/?z=1');
  }

  getZones(){
    return this.http.get(this.api_url+'/zones/');
  }

}

導航欄組件

導航欄組件利用category變量顯示不同的選項,因為訂閱位於該組件中,因此可以很好地工作。

import { Component, OnInit } from '@angular/core';
import { trigger, state, transition, animate, style } from '@angular/animations';
import { DataService } from '../data.service';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss'],
  animations: [
    trigger('slideInOut', [
      state('in', style({
        overflow: 'hidden',
        height: '*'
      })),
      state('out', style({
        overflow: 'hidden',
        height: '0px'
      })),
      transition('in => out', animate('400ms ease-in-out')),
      transition('out => in', animate('400ms ease-in-out'))
    ])
  ]
})
export class NavbarComponent implements OnInit {

  categories: Object;

  constructor(private data:DataService) { }

  ngOnInit() {
    this.data.getCategories().subscribe( data => {
      this.categories = data
      for(let category in this.categories){
        this.categories[category].productsOpen='out';
        for(let product in this.categories[category].product){
          this.categories[category].products[product].active = false;
        }
      }
      this.data.categories = this.categories;
    });
  }

  openProducts(index){
    this.categories[index].productsOpen = this.categories[index].productsOpen === 'out' ? 'in' : 'out';
  }

  setActiveProduct(index, productIndex){
    for(let category in this.categories){
      for(let product in this.categories[category].products){
        this.categories[category].products[product].active = false;
      }
    }
    this.categories[index].products[productIndex].active = true;
  }

}

家庭組件

我的Home組件還利用Categories變量,所以我想知道如何在這里獲取它,因為即使在服務中發生更改,它也始終是未定義的。

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  categories: Object;

  constructor(private data:DataService) { }

  ngOnInit() {
    this.categories = this.data.categories;
  }

}

我這樣做對嗎? 我習慣於進行響應和還原,並且在那里,每次調用setState更改狀態時,render方法都會運行,何時angular知道組件的變量何時更改? 我只想用數據保存一個全局變量,這樣我就可以重復使用它而無需每次都調用API。 謝謝。

您可以在服務中緩存可觀察對象,例如:

export class DataService {

someProperty;

  api_url: string = "https://apiurlhere";
  categories: Object;

  constructor(private http: HttpClient) { }

  getCategories(){
   if(!this.someProperty) {
     this.someProperty = this.http.get(this.api_url+'/categorylisting/?z=1');
   }
     return this.someProperty;
  }
}

您也可以使用有角度的Http攔截器,否則您也可以選擇rxjs運算符shareReplay

您可以嘗試在DataService的構造函數中調用API

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  api_url: string = "https://apiurlhere";
  categories: Object;

  constructor(private http: HttpClient) { 
    this.getCategories().subscribe(data => this.categories = data);
  }

  getCategories(){
    return this.http.get(this.api_url+'/categorylisting/?z=1');
  }

  getZones(){
    return this.http.get(this.api_url+'/zones/');
  }

}

然后就像在Home組件中一樣在NavBar組件中獲取類別。

  ngOnInit() {
    this.categories = this.data.categories;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM