[英]Filter array of objects by property value
I'm new with Angular and observables. 我是Angular和Observable的新手。 I'm getting from a JSON file a list of products. 我从JSON文件中获取产品列表。
products.service products.service
getProducts(): Observable<Product[]>{
return this._http.get<Product[]>(this.configUrl);
}
products.component products.component
products: Product[];
getProducts(): void{
this.productsService.getProducts()
.subscribe(products => this.products = products);
}
product.ts product.ts
export interface Product {
"quantity": number;
"price": string;
"available": boolean;
"sublevel_id": number;
"name": string;
"id": string;
}
Everything is working fine but I would like to filter the response to get only the products where available == true
一切正常,但我想过滤响应以仅获取available == true
的产品available == true
I tried in service and component some approaches but nothing worked. 我尝试在服务和组件中提供一些方法,但没有任何效果。 How can I achieve this in a proper way? 如何以适当的方式实现这一目标?
Code not working 代码不起作用
this.products = this.products.filter(product => {
return product.available == true
});
filterProducts(): Observable<Product[]>{
return this.getProducts()
.pipe(map(products => products
.filter(product => product.available === true)));
}
JSON response (not filtered) JSON响应(未过滤)
{ "products": [
{
"quantity": 308,
"price": "$8,958",
"available": false,
"sublevel_id": 3,
"name": "aute",
"id": "58b5a5b1b6b6c7aacc25b3fb"
},
{
"quantity": 891,
"price": "$5,450",
"available": true,
"sublevel_id": 3,
"name": "mollit",
"id": "58b5a5b117bf36cf8aed54ab"
},
{
"quantity": 698,
"price": "$17,001",
"available": false,
"sublevel_id": 10,
"name": "eiusmod",
"id": "58b5a5b18607b1071fb5ab5b"
}
]}
Try this. 尝试这个。
let o = { "products": [ { "quantity": 308, "price": "$8,958", "available": false, "sublevel_id": 3, "name": "aute", "id": "58b5a5b1b6b6c7aacc25b3fb" }, { "quantity": 891, "price": "$5,450", "available": true, "sublevel_id": 3, "name": "mollit", "id": "58b5a5b117bf36cf8aed54ab" }, { "quantity": 698, "price": "$17,001", "available": false, "sublevel_id": 10, "name": "eiusmod", "id": "58b5a5b18607b1071fb5ab5b" } ]} let filtered = o.products.filter(p => p.available===true) console.log(filtered);
use the filter operator inside the pipe
and do the normal subscription 在pipe
内使用filter运算符并进行常规订阅
filterProducts(): Observable<Product[]>{
return this.getProducts()
.pipe(
filter(products => product.available )
)
}
This should work. 这应该工作。
getProducts(): void{
this.productsService.getProducts()
.subscribe(products => this.products = products.filter(product=>product.available==true));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.