我对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 {{1并修改它(使用高图表)。但也许我应该在加载页面的其他一些方面做这一切?
我尝试使用this主题中所述的ngZone和ChangeDetectionStrategy,但我没有设法让它适用于我的案例。
任何帮助都会受到赞赏,即使它没有完全解决问题。
答案 0 :(得分: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();
}
}
答案 1 :(得分:3)
您应该使用箭头函数来使用词法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
关键字与您的组件实例不对应。
有关箭头函数词汇的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。
否则,我对您的代码有一个示例评论。您应该利用observable进行HTTP调用。就我所见,在你的代码中似乎并非如此......