【问题标题】:How do i get an object nested in another object using Angular如何使用 Angular 获取嵌套在另一个对象中的对象
【发布时间】:2020-04-21 18:16:18
【问题描述】:

我正在使用这样的 api 中的对象。

我可以获取数据,但无法独占获取 ChildSimpleProducts 数组。

这里是product.service函数

  getProducts = (): Observable<IProducts[]> => this.http.get<IProducts[]>(`${this.apiUrl + this.productsUrl}`);

这里是组件函数

  data: any = [];


productsArray: Observable<IProducts>[];
getProducts() {
this.productService.getProducts().subscribe(data => {
  this.data = data;
  this.productsArray = data["$values"];
  console.log(this.productsArray)
})

}

我已经尝试了一些东西,但不断得到未定义和未定义的对象

【问题讨论】:

  • 你试过this.productsArray[0].childSimpleProducts吗?
  • 你试过 data.$values;

标签: arrays json angular object


【解决方案1】:

使用forEach遍历所有productsArray,得到childSimpleProducts,

getProducts() {
 this.productService.getProducts().subscribe(data => {
  this.data = data;
  this.productsArray = data["$values"];
  this.productsArray.forEach( e => console.log(e.childSimpleProducts);
  //this.productsArray.filter( e => e.childSimpleProducts); // This will return you an array of childSimpleProducts
 })
}

【讨论】:

    【解决方案2】:

    如果你正确地从 api 获取数据然后data.$values 返回结果

    data: any = [];
    productsArray: Observable<IProducts>[];
    getProducts() {
        this.productService.getProducts().subscribe(data => {
          this.data = data;
          this.productsArray = data.$values;
          console.log(this.productsArray)
          this.productsArray.forEach(x=>{
              console.log(x.ChildSimpleProducts)
          })
        })
     }
    

    【讨论】:

    • @Çağrı,那部分已经在工作,所以我正在记录该对象,但我想专门获取子产品并将它们存储在单独的变量中跨度>
    • 啊抱歉我理解错了。然后你可以使用 foreach 输入每个嵌套结果
    • @Çağrı 你在复制我的答案。 :(
    【解决方案3】:

    使用加载破折号库到cloneDeep数组 https://lodash.com/docs/#cloneDeep

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2015-12-18
      • 2018-10-12
      相关资源
      最近更新 更多