我在如何在我的卡片上显示每个主题的数据方面遇到了问题。
HTML
<ion-item *ngFor="let topic of topicCluster" (click)="viewTopic(topic.slug)">
<strong>{{topic?.number}}. {{topic?.name}}</strong>
</ion-item>
TS
this.topicProvider.getClusters().subscribe(cluster => {
this.clusters = cluster
console.log(this.clusters)
cluster.forEach(element => {
const topicArr = []
for (var key in element.topics){
this.topicProvider.getTopic(key).subscribe(topic => {
topicArr.push(topic)
})
}
this.topicCluster = topicArr
console.log(this.topicCluster)
})
})
问题:
1st Card:
14th Topic
15th Topic
..
5th Card:
14th Topic
15th Topic
应该是:
1st Card:
14th Topic
15th Topic
..
5th Card:
14th Topic
15th Topic
这是我拥有的数据
发布于 2018-01-22 07:42:29
需要更新您的for循环,因为有一个异步订阅调用,它将丢失上下文。for循环将循环,并将键的最后一个值传递给异步。您可以使用IIFE来避免这种情况。
let self = this;
self.topicProvider.getClusters().subscribe(cluster => {
self.clusters = cluster
console.log(self.clusters);
cluster.forEach(element => {
const topicArr = []
for (var key in element.topics){
(function(keyData){
self.topicProvider.getTopic(keyData).subscribe(topic => {
topicArr.push(topic);
})
})(key);
}
self.topicCluster = topicArr
console.log(self.topicCluster)
})
})
https://stackoverflow.com/questions/48375978
复制