3

我对 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 来查找包含 id 的 divCompletion[...]并对其进行修改(在其上使用 highcharts )。但也许我应该在页面加载的其他点做这一切?我尝试使用本主题中所述的 ngZone 和 ChangeDetectionStrategy ,但我没有设法使其适用于我的案例。

任何帮助表示赞赏,即使它不能完全解决问题。

4

2 回答 2

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


}
于 2016-02-10T14:08:28.113 回答
3

您应该使用箭头函数才能使用 lexical 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 的更多提示,请参阅此链接:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 。

否则,我有关于您的代码的示例评论。你应该为你的 HTTP 调用利用 observables。据我所知,您的代码中似乎并非如此......

于 2016-02-10T14:08:02.567 回答