The For Loop does not work properly (Angular2)

advertisements

I'm wondering why am i getting a weird behavior using For Loop in Angular2 (TypeScript). I made this loop

 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]);
                            });
                    }
           });
     }

So that for every Question (in listQuestion) I called a service that would find all the propositions for this question (findPropositionByQuestion) using its wording (wordingQ) ; the problem is that it seems the loop is not working , when making the console.log(this.listQuestion[q]) it shows off only the last Question in the listQuestion duplicated as much as the number of the indexes in the listQuestion (so if i have 3 Questions, it shows me the last Question 3 times and so on..). For more explication: here i have 2 loaded Questions :

And here what the console.log is showing me :

Any Help please ?


You need to split your code with an additional method:

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);
      });
}

This question could help you to understand why you have several times the same element displayed in trace:

  • JavaScript closure inside loops – simple practical example