簡體   English   中英

通過http.get調用API並收到正確的JSON后,Angular2類未定義

[英]Angular2 Class undefined after calling API via http.get and receiving the correct JSON back

我有以下代碼(基於Angular2 Hero示例),並且我試圖將JSON API調用(AWS)轉換為TypeScript類。

代碼沒有返回錯誤,當我查看response.json()時可以看到對象在那里,但是類產品仍然未定義,有什么想法嗎?

服務文件中的代碼...

  getProduct(id: number): Promise<Product> {
    const url = `${this.ProductsUrl}/${id}`;
    console.log(url);
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Product)
      .catch(this.handleError);
  }

組件文件中的代碼...

  ngOnInit(): void {    
    this.route.params
      .switchMap((params: Params) => this.productsService.getProduct(+params['id']))
      .subscribe(product => this.product = product);
  }

班級...

export class Product {
  Instock: boolean;
  Description: string;
  CategoryId: number;
  Id: number;
  ColourOptions: string[];
  Name: string;
}

從API調用返回的JSON ...

{
"Instock":true,
"Description":"This is a test description.",
"CategoryId":1,"
Id":1,
"ColourOptions":["Red","Gold","Green"],
"Name":"Test"
}

switchMap必須返回一個Observable而不是Promise ,所以編輯getProduct來返回一個Observable

 getProduct(id: number): Observable<Product> {
    const url = `${this.ProductsUrl}/${id}`;
    console.log(url);
    return this.http.get(url)
      .map(response => response.json().data as Product)
      .catch(this.handleError);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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