繁体   English   中英

可观察的 rxjs 过滤器

[英]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转嫁给findRecommendedProductsundefined ,因为记录this.allProducts不包含值。

话虽如此,请注意,当您定义product: Product ,您只定义了它的类型,但尚未对其进行初始化。 因此默认值是undefined ——如果我没记错的话。

所以改变product: Productproduct: Product = {}; ,例如或在构造函数中或在ngInit传递一个值给它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM