首页 > 解决方案 > 问题得到非结构化对象 - Angular

问题描述

我是一个学生

为什么它返回未定义?这是我需要执行解构以仅获取两个值的对象。我可以获得完整的数组,但尝试非结构化它返回未定义。

服务

   getLastCashMov(): Observable<CashMov> {
    const url = `${this.API_URL}/last_cashmov`
    return this.http.get<CashMov>(url)
  }

零件

   getLastCashMov() {
    this.cashMovsService.getLastCashMov()
    .subscribe(({balanceARS, balanceUSD}) => 
      {  this.lastCashMovs = {balanceARS, balanceUSD};
        console.log(balanceARS, balanceUSD)
      }, error => {
        console.log(error)
      })
  }

返回

返回

使用时

  getLastCashMov() {
    this.cashMovsService.getLastCashMov()
    .subscribe((res) => 
      {  this.lastCashMovs = res;
        console.log(this.lastCashMovs)
      }, error => {
        console.log(error)
      })
  }

返回

在此处输入图像描述

解决方案

    getLastCashMov() {
    this.cashMovsService.getLastCashMov()
    .subscribe(([{balanceARS, balanceUSD}]) => 
      {  this.lastCashMovs = {balanceARS, balanceUSD};
        console.log(this.lastCashMovs)
      }, error => {
        console.log(error)
      })
  }

服务

  getLastCashMov(): Observable<CashMov[]> {
    const url = `${this.API_URL}/last_cashmov`
    return this.http.get<CashMov[]>(url)
  }

标签: javascriptangular

解决方案


我们不能Unstructure为某些键设置对象数组。我们需要通过map或更新和过滤密钥filter

这是代码:


getLastCashMov() {
this.cashMovsService.getLastCashMov()
.subscribe((responseArray) => {  
    let filteredArray = responseArray.map(item => return { balanceARS : item.balanceARS, balanceUSD: item.balanceUSD})   
    // filteredArray = [{ balanceARS : "...", balanceUSD: "..."}]
    this.lastCashMovs = filteredArray[0];
    console.log(balanceARS, balanceUSD)
  }, error => {
    console.log(error)
  })
}

推荐阅读