[英]How to get Json response from PHP which have Object and Array and Json array present inside Json Object
[英]Get array inside JSON API Response Object
我正在嘗試制作一個同時具有前端和后端的應用程序。 我都完成了,但現在我在嘗試連接它們時遇到了一些麻煩。 我不斷收到此錯誤:
catalog.component.ts:45 錯誤錯誤:NG0900:嘗試區分“[object Object]”時出錯。 DefaultIterableDiffer.diff (core.mjs:28514:19) 只允許數組和迭代
首先,我試圖獲取產品所在的數組“響應”:
產品.服務.TS
public getAll(): Observable<Product[]> {
return this.http.get<Response["response"]>(this.productsUrl);
}
此方法收到以下響應:
{
"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",
}
]
}
然后,當我的目錄頁面打開時,我運行這兩個函數:
目錄.組件.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")
});
}
但我不斷收到 NG0900 錯誤。 我相信這可能是因為我沒有讀取產品所在的數組。
我已經更改了 getAll 方法,因為它原來是這樣的:
public getAll(): Observable<Product[]> {
return this.http.get<Product[]>(this.productsUrl);
}
我也嘗試在這里搜索其他響應,但似乎沒有一個適用於我的問題,或者我可能只是一個新手,看不到這種關系。 有誰知道我在這里做錯了什么? 提前致謝。
您的 JSON 響應是一個對象。
export interface ProductListResponse {
httpCode: Number;
message: string;
response: Product[];
}
使用rxjs
中的map
從response
屬性返回數組。
import { map } from 'rxjs';
public getAll(): Observable<Product[]> {
return this.http.get<ProductListResponse>(this.productsUrl)
.pipe(map((data) => data.response));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.