2016-12-12 2 views
0

HTTP getサービスを使用して設定されたプロパティを使用中にエラーが発生します。以下は私のコードです:HTTPを使用してAngular2でデータを取得

ngOnChanges(changes: any){ 
    // this.queslist = this.quizdalservice.getQuizQuestions(this.name); 
    this.quizdalservice.getQuizQuestions(this.name).then(mcquiz => this.queslist = mcquiz); 
    console.log('hi'); 
    for(let ques of this.queslist) 
    { 
     this.max_score +=ques.score; 
    } 
} 

未定義のプロパティで長さを使用するようなエラーが表示されます。サービスがPromiseを使用してデータを返すので、forループが原因であると想定します。

return this.http.get(this.quizquestionUrl) 
      .toPromise() 
      .then(response => response.json().data as mcquestion[]) 
      .catch(this.handleError); 

進める方法をご提案ください。質問が読み込まれると最大マークを設定したいので、ngOnChangesメソッドで行う必要があります。その後、コールバックで

+0

なぜngOnChangesメソッドを使用しているのかわかりません。しかし、あなたの問題を解決するかもしれない以下のコードを試してください。コードの下の – micronyks

+0

@micronyksが機能しています。ありがとう。質問リストは選択したクイズに応じて変更できるので、ngOnChangeを使用しています。 –

+0

助けがあれば、それを受け入れられた回答としてマークすることができます。 – micronyks

答えて

0
ngOnChanges(changes: any){ 
    // this.queslist = this.quizdalservice.getQuizQuestions(this.name); 
    this.quizdalservice.getQuizQuestions(this.name) 
     .then(mcquiz => { 

         this.queslist = mcquiz; 

         console.log('hi'); 
         for(let ques of this.queslist) 
         { 
          this.max_score +=ques.score; 
         } 

     }); 

} 
0
this.quizdalservice.getQuizQuestions(this.name).then(mcquiz => this.queslist = mcquiz); 
    console.log('hi'); 
    for(let ques of this.queslist) //data has not arrieved yet 
    { 
     this.max_score +=ques.score; 
    } 

移動ループ!

this.quizdalservice.getQuizQuestions(this.name).then(mcquiz => { 
    this.queslist = mcquiz 
    for(let ques of this.queslist)//data has arrieved 
    { 
     this.max_score +=ques.score; 
    } 
}); 
console.log('hi'); 
関連する問題