[英]Observable rxjs filter
在我的項目中,我想在每個產品頁面中創建某種“推薦產品”,但是在使我的功能過濾成為可觀察的方面遇到了麻煩。
我曾嘗試以不同的方式使用 .pipe(filter()) ,但沒有用。
基本上功能應該過濾具有相同類型和id 的產品,並將它們顯示在正確的產品頁面中,但在訂閱我的所有產品后幾乎卡住了(標記如下)。
非常感激!
import { Component, OnInit } from '@angular/core'; import { ProductService } from '../services/product.service'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import Product from '../interfaces/product'; import { map, filter} from 'rxjs/operators'; import { Observable } from 'rxjs'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { recommandedProducts: Product[]; allProducts:Product[]; // allProducts:Observable< Product> = new Observable< Product>(); product: Product; constructor(private productService: ProductService, private route: Router, private actRoute: ActivatedRoute) { } ngOnInit() { this.findRecommendedProducts(this.product) }; //From ProductService: // getProducts(){ // return this.http.get(`${this.uri}`); // } findRecommendedProducts(currectProduct: Product){ this.productService.getProducts().subscribe((data: Product[]) => { this.allProducts = data; console.log(this.allProducts) this.recommandedProducts = this.allProducts.filter(otherProduct => otherProduct.type == currectProduct.type && otherProduct.id == currectProduct.id) console.log(this.recommandedProducts); }); }; }
rxjs 中的過濾器與 Array.filter Array.filter
。 在 rxjs 中,過濾器用於發出滿足提供條件的值。 因此,如果您使用過濾器,根據條件,可觀察對象要么發出您的數據,要么不返回任何內容。
相反,您需要的是pipe(map)
和Array.filter
。 此外,正如@jzzfs 所指出的,您的錯誤顯示currentProduct
可能是undefined
,因此您可以在findRecommendedProducts
函數中傳遞一個默認值。
試試下面的代碼。
findRecommendedProducts(currectProduct: Product = {} as Product) {
this.productService.getProducts()
.pipe(
map((products: Product[]) => products.filter(product => product.type == currectProduct.type && product.id == currectProduct.id))
)
.subscribe((data: Product[]) => {
this.recommandedProducts = data;
});
};
現在您訂閱的數據應該直接返回recommendedProducts
。
像看起來currectProduct
轉嫁給findRecommendedProducts
是undefined
,因為記錄this.allProducts
不包含值。
話雖如此,請注意,當您定義product: Product
,您只定義了它的類型,但尚未對其進行初始化。 因此默認值是undefined
——如果我沒記錯的話。
所以改變product: Product
到product: Product = {};
,例如或在構造函數中或在ngInit
傳遞一個值給它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.