For循环无法正常工作(Angular2)

问题描述:

我想知道为什么我会在Angular2 (TypeScript)中使用For循环得到奇怪的行为。我做了这个循环For循环无法正常工作(Angular2)

loadAllQuestions() { 

      this.questionService.loadAllQuestions() 
       .map(res=>res.json()) 
       .subscribe(res=>{ 
        this.listQuestion = res.questions; 
        for (var q in this.listQuestion){ 
         this.propositionService.findPropositionByQuestion(this.listQuestion[q].wordingQ) 
          .map(res=>res.json()) 
          .subscribe(res=>{ 
           console.log(this.listQuestion[q]); 
          }); 
        } 
      }); 
    } 

所以,每Question(在listQuestion)我叫使用它的措辞(wordingQ)服务将找到这个问题的所有命题(findPropositionByQuestion);问题是,它似乎循环不工作,当使console.log(this.listQuestion[q])它只展示listQuestion中的最后一个问题与listQuestion中索引的数目一样多(所以如果我有3个问题,它显示我最后一个问题3次等等。)。 详细阐释:在这里,我有2个问题加载:

enter image description here

这里什么的console.log是我展示:

enter image description here

任何帮助吗?

+1

[臭名昭著的Javascript循环问题?(http://*.com/questions/1451009/javascript-infamous-loop-issue) –

你需要一个额外的方法来分割你的代码:

loadAllQuestions() { 
    this.questionService.loadAllQuestions() 
    .map(res => res.json()) 
    .subscribe(res => { 
     this.listQuestion = res.questions; 
     for (var q in this.listQuestion) { 
     this.findProposition(this.listQuestion[q]); 
     } 
    }; 
} 

findProposition(question) {       
    this.propositionService.findPropositionByQuestion(
    question.wordingQ) 
     .map(res => res.json()) 
     .subscribe(res => { 
     console.log(question); 
     console.log(res); 
     }); 
} 

这个问题可以帮助你理解为什么你有几次跟踪显示相同的元素:

我建议你试试for (var q of this.listQuestion){...}而不是for (var q in this.listQuestion){...}

+0

没有工作,但由于可能的重复无妨;) –

您可以使用let关键字使q变量块作用域。

for (let q in this.listQuestion){ //var --> let 
    this.propositionService 
     .findPropositionByQuestion(this.listQuestion[q].wordingQ) 
     .map(res=>res.json()) 
     .subscribe(res=>{ 
      console.log(this.listQuestion[q]); 
     }); 
} 
+0

这需要Emascript 6或更高版本,感谢无论如何:) –

+0

@Selem喜欢如果箭头功能不:)你仍然使用打字稿。它不处理让你变成var变换吗? –

+0

https://www.typescriptlang.org/play/#src=for%20(let%20q%20in%20obj)%7B%0D%0A%20%20%20%20doSomethingAsync(res%3D%3E%7B %0D%0A%20%20%20%20%20%20%20%20%20%20%20%20obj%件5bq%5D%0D%0A%20%20%20%20%7D)%3B% 0D%0A%7D –