Angular数组显示所有视图中的最后数据

时间:2018-01-22 06:47:10

标签: arrays angular for-loop ionic3

我在如何显示卡片上每个主题的数据方面遇到了问题。

HTML

<ion-item *ngFor="let topic of topicCluster" (click)="viewTopic(topic.slug)">
  <strong>{{topic?.number}}.&nbsp;{{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

这是我拥有的数据enter image description here

1 个答案:

答案 0 :(得分:0)

需要更新你的for循环,因为有一个asynsubscribe调用,它会松开上下文。 for循环将循环,密钥的最后一个值将传递给async。你可以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)
    })
  })