I'm trying to make an application with both front-end and back-end. I have finished both, but now I'm having some trouble trying to connect them. I keep getting this error:
catalog.component.ts:45 ERROR Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed at DefaultIterableDiffer.diff (core.mjs:28514:19)
First, I'm trying to get the array response
, where the products are located:
product.service.ts
public getAll(): Observable<Product[]> {
return this.http.get<Response["response"]>(this.productsUrl);
}
This method receives the following response:
{
"httpCode": 200,
"message": "OK",
"response": [
{
"pieceName": "Mini Figure Trophy",
"pieceImageURL": "https://www.lego.com/cdn/product-assets/element.img.lod5photo.192x192/6335932.jpg",
"piecePrice": 0.3,
"pieceTag": "Bestseller",
},
{
"pieceName": "Animal No. 17 Dog",
"pieceImageURL": "https://www.lego.com/cdn/product-assets/element.img.lod5photo.192x192/6076467.jpg",
"piecePrice": 2.76,
"pieceTag": "Bestseller",
}
]
}
Then, when my catalog page opens, I run these two functions:
catalog.component.ts
ngOnInit(): void {
this.getProducts();
this.searchSubject.subscribe(value => this.searchService.setSearchValue(value));
this.searchService.searchValue$.subscribe(value => {
this.productService.getProductByNameLike(value).subscribe(productsCalled => {
this.products = productsCalled})
})
}
getProducts(): void {
this.productService.getAll().subscribe({ <- Line where the error occurs
next: (productsCalled: Product[]) => {
this.products = productsCalled
this.checkProductsOnCart()
},
error: (err) => console.log(err),
complete: () => console.log("completo")
});
}
But I keep getting the NG0900 error. I believe it might be because I'm not reading the array where the products are.
I have changed the getAll
method, as originally it was:
public getAll(): Observable<Product[]> {
return this.http.get<Product[]>(this.productsUrl);
}
I also tried searching for other responses here, but none seem to be applicable to my problem, or maybe I'm just too much of a newbie to see the relation. Does anyone know what am I doing wrong here? Thanks in advance.
CodePudding user response:
Your JSON response is an object.
export interface ProductListResponse {
httpCode: Number;
message: string;
response: Product[];
}
Work with map
from rxjs
to return the array from the response
property.
import { map } from 'rxjs';
public getAll(): Observable<Product[]> {
return this.http.get<ProductListResponse>(this.productsUrl)
.pipe(map((data) => data.response));
}