异步通话不起作用

时间:2018-08-06 12:28:38

标签: angular

在我的BrandComponent类的ngInit函数中,我对我的BrandService对象的filterProduct()函数进行了异步调用。

ngOnInit() {
    this.brandSidebarService.sidebarData$.subscribe(sidebarData => {
      this.brandService.filterProducts(sidebarData).subscribe(products => {
        this.products = products;
      })
    })
  }

这是BrandService类的filterProducts()函数:

public filterProducts(productFilters) {
    this.dataService.getProducts().subscribe(products => {
      let filteredProducts = products;
      filteredProducts = this.filterByBrands(productFilters[0], 
         filteredProducts);
      filteredProducts = this.filterByPrices(productFilters[1], 
         filteredProducts);
      filteredProducts = this.filterByRating(productFilters[2], 
          filteredProducts);  

      return of(filteredProducts);
    })
  }

在BrandComponent ngInit函数中,即使BrandService的filterProducts()返回一个可观察值,我也会从下面所示的订阅中收到以下错误。

this.brandService.filterProducts(sidebarData).subscribe(products...

[ts] Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您已经订阅了从this.dataService.getProducts()返回的Observable( filterProducts结果)。如果您想对结果数据做额外的工作,只需将pipegetProducts函数并添加额外的映射器(map),即可映射结果。

import { map } from 'rxjs/operators';

public filterProducts(productFilters) {
    return this.dataService.getProducts().pipe(
       map(products => {
             let filteredProducts = products;
             filteredProducts = this.filterByBrands(productFilters[0], filteredProducts);
             filteredProducts = this.filterByPrices(productFilters[1], filteredProducts);
             filteredProducts = this.filterByRating(productFilters[2], filteredProducts);  

             return filteredProducts;
       })
    );
}

答案 1 :(得分:1)

首先,该错误与您发布的代码不匹配。它抱怨subscribe类型的Subscription中不存在,但是您的方法实际上没有返回Subscription。它不返回任何内容(即undefined)。

不订阅。使用map运算符将事物的可观察性转换为事物的可观察性。请注意,您没有在任何地方指定类型,从而防止TypeScript在编译时发现错误,从而使自己陷入困境。因此,在这里我将使用虚构类型,因为我不知道它们实际上是什么:

public filterProducts(productFilters: Array<ProductFilter>): Observable<Product> {
  // note the return keyword on the next line, which is necessary for your method to return something

  return this.dataService.getProducts().pipe(
    map(products => {
      let filteredProducts = products;
      filteredProducts = this.filterByBrands(productFilters[0], filteredProducts);
      filteredProducts = this.filterByPrices(productFilters[1], filteredProducts);
      filteredProducts = this.filterByRating(productFilters[2], filteredProducts);  

      return filteredProducts;
    })
  );
}