使用HTTP获取Angular2

时间:2016-12-12 14:34:48

标签: angular

在使用使用HTTP get service设置的属性后,我收到错误。以下是我的代码:

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

我收到的错误就像在未定义的属性上使用Length一样。我认为这是因为for循环,因为服务使用Promise来返回数据。

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

请建议如何继续。我想在加载问题后设置最大标记,并且应该在ngOnChanges方法中完成。

2 个答案:

答案 0 :(得分: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;
                        }

         });

}

答案 1 :(得分: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');