问题描述
我看到这个问题被问了很多,但我找不到一个明确的解释来解释为什么我的代码不起作用!
getItemValueHistory(ids: number) {
this.itemResource.getItemValueHistory(ids).subscribe(
(res: ItemItemValueHistory[]) => {
res.forEach((itemHistory) => {
const history = itemHistory.second.listofPrices.map(values => values.currentPrice);
const item = itemHistory.first;
this.simpleCharts.push(this.createSimpleChart(item,history));
});
}
);}
所以这个函数会生成一个 id 数组,它将从后端获取一些值(我知道响应的命名不是很清楚,但这一切都将在稍后修复)。
在 HTML 方面,有一个 ngFor 循环遍历数组 simpleCharts。
<div class="col-sm-4" *ngFor="let simpleChart of simpleCharts">
<app-simple-graph [simpleChart]="simpleChart"></app-simple-graph>
</div>
我遇到的问题是,当我尝试将我从后端得到的响应拆分为一个项目和一个历史记录部分时。历史上的 map 总是失败,因为我无法读取未定义的列表。我以为当我在订阅中执行代码时,这只会在您获得可观察对象时运行?
可能我遗漏了一些非常明显的东西,但很想知道它是什么!
根据亚历山大更新代码的建议:这仍然给我一个类型错误:无法读取 itemHistory.second.listofPrices.map 处未定义错误的属性“地图”
getItemValueHistory(ids: number) {
this.itemResource.getItemValueHistory(ids)
.pipe(
map((itemHistories: ItemItemValueHistory[]) => {
return itemHistories.map(itemHistory => {
const history = itemHistory.second.listofPrices.map(values => values.currentPrice);
const item = itemHistory.first;
return this.createSimpleChart(item,history);
});
})
).subscribe(res => {
return this.simpleCharts.push(res);
});
}
解决方法
问题是 simpleCharts
似乎不是 Observable<T>
并且您没有使用诸如 async
之类的管道来等待 Observable
发出.尝试这样的事情,使用 RxJS map
运算符创建一个使用 Array.prototype.map
的图表数组:
getItemValueHistory(ids: number) {
return this.itemResource.getItemValueHistory(ids)
.pipe(
map((itemHistories: ItemItemValueHistory[]) => {
return itemHistories.map(itemHistory => {
const history = itemHistory.second.listOfPrices.map(values => values.currentPrice);
const item = itemHistory.first;
return this.createSimpleChart(item,history);
});
})
);
}
然后您可以将该 Observable
保存到类属性以与 async
管道一起使用:
<div class="col-sm-4" *ngFor="let simpleChart of simpleCharts$ | async ">
<app-simple-graph [simpleChart]="simpleChart"></app-simple-graph>
</div>
或将 subscribe
改为 getItemValueHistory
并使用发出的映射值更新 this.simpleCharts
,确保将 simpleCharts
初始化为空数组:
// make sure to initialize an empty array of the appropriate type
simpleCharts = [];
getItemValueHistory(ids: number) {
this.itemResource.getItemValueHistory(ids)
.pipe(
map((itemHistories: ItemItemValueHistory[]) => {
return itemHistories.map(itemHistory => {
const history = itemHistory.second.listOfPrices.map(values => values.currentPrice);
const item = itemHistory.first;
return this.createSimpleChart(item,history);
});
})
).subscribe(res => this.simpleCharts = res);
}
希望有帮助!
,看到这个问题打开了。最终,这是一个非常菜鸟的错误,没有正确地将响应映射到对象。我错过了一封信,所以它从来没有被映射过,而且总是未定义,哎呀 :)