簡體   English   中英

獲取 JSON API 響應對象中的數組

[英]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中的mapresponse屬性返回數組。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM