简体   繁体   中英

rjxs filter() don't seem to work on angular 9

products.json:

[{
    "id": 1,
    "imagem": "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjEzOTExNH0",
    "rating": 3,
    "title": "Product 1",
    "slug": "product-1",
    "description": "Dolor ullamco incididunt sit do deserunt proident anim cillum sunt consequat quis amet qui nostrud. Commodo et consequat sint ullamco ea sunt commodo sunt culpa aute. Incididunt eiusmod aute aute aliquip voluptate voluptate labore consequat commodo voluptate. Proident mollit nisi quis in nisi occaecat amet incididunt labore adipisicing exercitation enim qui est. Dolore esse ad do sint non. Ea ad dolor consectetur ex veniam.",
    "price": "55.63",
    "stock": 44
},...]

products service:

show(slug: string) : Observable<any> {
    return this.http.get('/assets/products.json').pipe(filter((product: Product) => product.slug == slug );
}

when I make this call no data comes:

this.productService.show('product-1').subscribe((product: Product) => {
     console.log(product); // nothing
});

when I use map() to debug:

show(slug: string) : Observable<any> {
     return this.http.get('/assets/products.json').pipe(map((product: Product) => console.log(product))); 
     // Log: (23) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
}

does anyone know why it doesn't work with filter()?

as @Alexander Staroselsky mentioned in the comment, you need to first map it and then call filter, as http.get returns an Observable, you can't call directly filter on it.

show(slug: string) : Observable<Product[]> {
    this.http.get<Product[]>('/assets/products.json').pipe(map(products => products.filter(product => product.slug == slug )))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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