HttpClient如何在Angular 7中转换嵌套的json并映射到模型

时间:2018-11-26 12:45:40

标签: angular typescript angular7

我已经嵌套了JSON对象,并且希望将其与Angular 7 private categoryModule: CategoryModel[] = [];一起存储在数组HttpClient中。

JSON对象:

[
  {
    id: 1, name: 'Mr. Nice', descriptio: 'dasdad', image: "sada", product: [
      { id: 0, name: 'Milos', descriptio: "sdada", number: 1, image: 'ssad' },
    ]
  },
  {
    id: 2, name: 'Misko', descriptio: 'dasdad', image: "sada", product: [
      { id: 0, name: 'Milos', descriptio: "sdada", number: 1, image: 'ssad' },
      { id: 1, name: 'Somi', descriptio: "haha", number: 1, image: 'haha' }
    ]
  }
]

我的模型ProductModel是:

export class ProductModel  {

  constructor(
    public id:number,
    public name: string, 
    public description: string, 
    public numberOfProduct: number, 
    public image: string) {}
}

我的模型CategoryModel:

export class CategoryModel  {

  public id: number;
  public name: string;
  public description: string;
  public image: string;
  public products: ProductModel[] ;


  constructor(
      name: string, 
      desciption: string, 
      image: string = null, 
      products: ProductModel[], 
      id: number) {
    this.id = id;
    this.name = name;
    this.description = desciption;
    this.image = image;
    this.products = products;
  }
}

这是我对get方法的服务:

  /** GET heroes from the server */
  getCategory(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
    /* map(products => {
        return Object.values(products)

      }),*/
      catchError(this.handleError('getProduct', []))
    )
  }

这是我用于在Array中存储数据的代码组件。

 getCagegoryFromServer() {
    this.dataStorageServiceServiceta.getCategory().subscribe((category :CategoryModel[]) => {

      this.categoryModule = category;
      console.log(this.categoryModule[0].products[0] + "milos car");
    })
  }

我的categoryModule数组出现问题,因为productsundefined。显然products未初始化。有什么知道如何解决的吗?

1 个答案:

答案 0 :(得分:2)

如果要将JSON响应映射到模型类,则需要将json响应映射到模型类:

getCategory(): Observable<CategoryModel[]> {
  return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
    map(categories => categories.map(categoryJson => new CategoryModel(
      categoryJson.name, 
      categoryJson.descriptio, 
      categoryJson.image, 
      categoryJson.product.map(productJson => new ProductModel(
        productJson.id,
        productJson.name, 
        productJson.descriptio, 
        productJson.number, 
        productJson.image
      )),
      categoryJson.id
    ))),
    catchError(this.handleError('getProduct', []))
  )
}

话虽如此,目前尚不清楚为什么要映射到javascript类,因为您的类似乎没有与之关联的任何方法。正如一些评论所指出的那样,您可以直接使用返回的json,并使用打字稿接口提供IntelliSense /错误检查。

如果您要坚持使用javascript类,则在类构造函数中使用单个options参数而不是单个属性参数将使事情变得简单。

例如

export class CategoryModel  {

  public id: number;
  public name: string;
  public description: string;
  public image: string;
  public products: ProductModel[] ;


  constructor(args: {
    name: string, 
    desciptio: string, 
    image: string = null, 
    product: {
      id: number,
      name: string, 
      descriptio: string, 
      number: number, 
      image: string
    }[], 
    id: number
  }) {
    this.id = args.id;
    this.name = args.name;
    this.description = args.desciptio;
    this.image = args.image;
    this.products = args.product.map(json => new ProductModel(json));
  }
}

这会将getCategory()方法简化为:

getCategory(): Observable<CategoryModel[]> {
  return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
    map(categories => categories.map(categoryJson => new CategoryModel(categoryJson))),
    catchError(this.handleError('getProduct', []))
  )
}