SeleM
SeleM

Reputation: 9678

The For Loop is not working in an appropriate way (Angular2)

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 :

enter image description here

And here what the console.log is showing me :

enter image description here

Any Help please ?

Upvotes: 1

Views: 965

Answers (3)

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

You can make q variable block scoped using let keyword.

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

Upvotes: 2

musale
musale

Reputation: 584

I suggest you try for (var q of this.listQuestion){...} instead of for (var q in this.listQuestion){...}

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202316

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:

Upvotes: 1

Related Questions