我对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是否正常检测到这个周末改变的事实.
然后我不知道我是否应该使用ngAfterViewInit函数来完成我的工作.问题是我开始这样做,因为在我的courseCompDiagram中我需要使用jquery来查找包含id Completion […]的div修改它(使用高图表).但也许我应该在加载页面的其他一些方面做这一切?
我尝试使用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关键字与您的组件实例不对应.
有关箭头函数词汇的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.
否则,我有关于您的代码的示例评论.您应该利用observable进行HTTP调用.就我所见,在您的代码中似乎并非如此……
原文地址:https://codeday.me/bug/20190727/1556037.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。