Angular2 类未定义后通过 http.get 调用 API 并接收正确的 JSON 返回



我有以下代码(基于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'callback 必须返回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);
  }

最新更新