回调后 Angular2 变化检测不起作用

Angular2 change detection not working after callback

我对 angular2 很陌生,我对变化检测有疑问。 在我的页面加载时,我需要调用一些 API 来获取构建我的网页的信息。我所做的是,当我收到此信息(包含在一个数组中)时,我想使用 *ngFor 遍历它。这是我的课程组件代码。

import {Component,Input} from 'angular2/core';
import {courseCompDiagram, sepExInWeeks} from "../js/coursesTreatment.js";
import {getSampleWeeks} from "../js/courseMng.js";

@Component({
    selector: 'course',
    directives:[Exercises],
    template: `
    <div class="course">
        <h2>{{aCourse.name}}</h2>
        <div class='diag-container row'> 
            <div id="Completion{{aCourse.name}}"></div>

            <div *ngFor="#week of weeks"> {{week.weekNb}} </div>
        </div>
    </div>`
})

export class Course{
    //This is inputed from a parent component
    @Input() aCourse;
    this.weeks = [];

    ngAfterViewInit(){
        //I call this method and when the callbacks are finished,
        //It does the following lines
        courseCompDiagram(this.aCourse, function(concernedCourse){
            //When my API call is finished, I treat the course, and store the results in weeks
            this.weeks = sepExInWeeks(concernedCourse.course.exercises);
        });
        //This is not supposed to stay in my code,
        //but is here to show that if I call it here,
        //the weeks will effectively change
        this.weeks = getSampleWeeks();
    }


}

所以首先,我想知道 angular2 没有检测到 this.weeks 改变的事实是否正常。 然后我不知道我是否应该使用 ngAfterViewInit 函数来完成我的工作。问题是我开始这样做是因为在我的 courseCompDiagram 中我需要使用 jquery 来找到 div 包含 id Completion[...] 并修改它(在其上使用 highcharts)。但也许我应该在页面加载的其他时间点完成所有这些工作? 我尝试使用 主题中所述的 ngZone 和 ChangeDetectionStrategy,但我没能成功解决我的问题。

感谢任何帮助,即使它不能完全解决问题。

您应该使用箭头函数才能使用词法 this,如下所述:

courseCompDiagram(this.aCourse, (concernedCourse) => {
  // When my API call is finished, I treat the course,
  // and store the results in weeks
  this.weeks = sepExInWeeks(concernedCourse.course.exercises);
});

关于原始回调,this 关键字与您的组件实例不对应。

有关箭头函数的词法 this 的更多提示,请参阅此 link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

否则我有一个关于您的代码的示例评论。您应该为 HTTP 调用利用可观察对象。据我所见,您的代码似乎并非如此...

export class Course{
    //This is inputed from a parent component
    @Input() aCourse;
    this.weeks = [];

    constructor(private _zone:NgZone) {}

    ngAfterViewInit(){
        //I call this method and when the callbacks are finished,
        //It does the following lines
        courseCompDiagram(this.aCourse, (concernedCourse) => {
            //When my API call is finished, I treat the course, and store the results in weeks
            this._zone.run(() => {
              this.weeks = sepExInWeeks(concernedCourse.course.exercises);
            });
        });
        //This is not supposed to stay in my code,
        //but is here to show that if I call it here,
        //the weeks will effectively change
        this.weeks = getSampleWeeks();
    }


}