【发布时间】:2020-07-09 06:55:40
【问题描述】:
我已经建立了我的在线商店项目 (Angular) 并尝试在每个产品页面中创建某种“推荐”区域。
起初我想订阅我所有的产品,然后查看它们以找到匹配的类型和 ID。
只是为了测试,我在我的 MongoDB 中创建了 18 个产品(6 个不同的产品)(3 个具有相同类型和 id 的相同产品的产品),但不幸收到此错误并且无法弄清楚原因:
无法读取未定义的属性“过滤器” 在 ProductComponent.findRecommandedProducts
export class ProductComponent implements OnInit {
recommandedProducts: Product[];
allProducts: Product[];
product: Product;
constructor(private productService: ProductService, private route: Router, private actRoute: ActivatedRoute) { }
ngOnInit() {
this.recommandedProducts = this.findRecommandedProducts(this.product)
};
findRecommandedProducts(currectProduct: Product){
this.productService.getProducts().subscribe((data: Product[]) => {
this.allProducts = data;
});
//productService.getProducts() returns all of my products in JSON format to localhost//
let recommandedProducts = this.allProducts.filter(otherProduct =>
otherProduct.type == currectProduct.type && otherProduct.id == currectProduct.id)
// otherProduct.id == currectProduct.id becacuse i have 3 identical items of each item. //
return recommandedProducts;
};
}
【问题讨论】:
-
你好摩西,欢迎来到 StackOverflow!您需要在 .subscribe() 代码块内进行过滤。那是您确定您已从后端/服务/数据提供商那里收到答复的地方。
标签: javascript angular typescript rxjs