javascript - 问题得到非结构化对象 - 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)
}
解决方案
我们不能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)
})
}
推荐阅读
- angular - Angular Services:我应该在组件中复制服务属性吗?
- json - 如何拆分包含 JSON 的 txt 文件?
- c++ - 通过多线程 C++ GTKMM 运行 UI,每 5 秒获取一次传感器信息
- java - 如何在 Firebase 中的子项中添加值子项?
- android - FirebaseAuthException 虽然被捕获,但抛出
- dart - 关于 dart 中 swift 样式扩展的问题,在 dart 中可以实现吗?
- python - 在 python 正则表达式中回顾
- java - 下面的while循环可以运行多次吗?
- java - 如何在 .JAR 文件中执行此代码,但在 IDE 中有效
- javascript - 在几个非 html 字符后拆分 html 文本