首页 文章

仅当父组件使用Angular4返回一个observable时,如何在子组件上调用函数

提问于
浏览
0

“简而言之:发出一个HTTP请求并将该数据传递给所有组件 . 问题是其他组件在从初始HTTP请求返回响应之前运行 . 所有组件只是从HTTP响应对象中提取数据位“ - 使用Angular 4 .

非常感谢任何帮助,谢谢 .

基本上,我的父组件调用加载我的JSON的服务 . 在服务方法中,我使用rxjs BehaviorSubject将我的HTTP请求的响应分配给Observable,以便我可以访问和跟踪订阅它的所有组件 . 想想我可以只调用一次我的服务器,只需在我的所有组件中抓取我想要的部分,而不是多次调用服务器 . 也许我会犯这个错误......最有可能的是 .

我的父母组成部分:

constructor(private _service: ProductsService, private data:DataService) { 
   this.getCatgegories(this.masterProduct);
}

我的服务方式:

private productCategoriesList = new BehaviorSubject<any>([]);
currentList = this.productCategoriesList.asObservable();

changeCatList(categoriesList){
   this.productCategoriesList.next(categoriesList);
}

getCatgegories(masterProduct: number) {
  return this.http
    .get(this.url)
    .map(response => {
    let productArray = response.json()[0].products;
    let henry = this.getFields(productArray, 'product');
    this.changeCatList(henry);
    //some parsing of object to get the returned value

    return catObj;
    });
}

1 回答

  • 0

    你的第一个问题的答案是你正确的方法 . 如果您想通知所有订阅您的服务的组件是根据您的要求从服务器处理数据的好方法 .

    这种方法也适用于组件不是父子组件的情况,因此它适用于所有组件 .

    你也可以想到 @Input@Output 如果它的父子和发射和事件在变化和猫捕获其他组件 . 但是你的方法在大量组件中运行良好 .

    你的方法和纠正 .

    在您的服务中,您将公开2个可以订阅的可观察对象 . 当 getCatgegories(masterProduct: number) 返回一个observable时,您可以订阅它并获取如下所示的数据

    所以更改您的服务以检查数据是否可用然后返回或者调用该服务 .

    // check if the method is called once then directly get the value from `BehavourSubject` or else call the method to get the data.
    private productCategoriesList = new BehaviorSubject<any>([]);
    currentList = this.productCategoriesList.asObservable();
    
    changeCatList(categoriesList){
       this.productCategoriesList.next(categoriesList);
    }
    
    getCatgegories(masterProduct: number) {
      const availableData = undefined;
      this.currentList.subscribe((data) => {
       if(data !==[]) { availableData  = data; }
      });
    
      if(availableData !== undefined ) {
        return this.http
        .get(this.url)
        .map(response => {
        let productArray = response.json()[0].products;
        let henry = this.getFields(productArray, 'product');
        this.changeCatList(henry);
        //some parsing of object to get the returned value
    
        return catObj;
        });
        } else {
          return this.currentList;
        } 
    }
    

    解决您的问题

    constructor(private _service: ProductsService, private data:DataService) { 
       this.ProductsService.getCatgegories(this.masterProduct).subscribe(( data) => {
          // do some operation into data
       });
    }
    

相关问题