打字稿:错误 TS2740:类型 '{}' 缺少类型 'Product[]' 的以下属性:length、pop、push、concat 等 26 个

Pin*_*nka 4 observable firebase angular switchmap

使用 Angular 4,我从 observable 中的 firebase db 获取数组列表。如何将 observable 的类型更改为数组,反之亦然以使其工作?

我写的没有不同的功能。我正在使用一个内置函数 switchMap,在其中分配一个 Products 数组。我无法弄清楚如何将可观察的 switchMap 更改为数组可观察。

constructor(
    route:ActivatedRoute,
    productService: ProductService ) { 
      productService
        .getAll()
        .switchMap(products => {
      //getting compile error at below line for this.products
          this.products = products;
          return route.queryParamMap;
        })
        .subscribe(params => {
          this.category = params.get('category');
          this.filteredProducts = (this.category) ? 
            this.products.filter(p => p.category === this.category) :
            this.products;
    });
  }
Run Code Online (Sandbox Code Playgroud)

switchMap observable 一次返回一项的结果,这里有一个数组列表。我如何使它工作。

Pin*_*nka 6

我想到了。:) 我将product.service.ts 中方法的返回类型更改为可观察的产品数组

 getAll(): Observable<Product[]>{
 return this.db.list('/products');//to get list of all products
}
 get(productId): Observable<Product[]>{
 return this.db.object('/product/' + productId);
}
Run Code Online (Sandbox Code Playgroud)