我有一个非常简单的Angular2组件:
@Component({
moduleId: module.id,
selector: 'app-people',
templateUrl: 'people.component.html'
})
export class PeopleComponent implements OnInit {
people: any[] = [];
constructor(private peopleService: PeopleService) {
}
ngOnInit() {
this.peopleService.getPeople()
.subscribe(this.extractPeople);
}
extractPeople(result: any) {
this.people = result.people;
}
}
在初始化时,我看到ngOnInit()
被调用,调用peopleService.getPeople()
。我还看到调用extractPeople()
的异步返回。但是,即使在this.people
更新后,组件也不会重新呈现。为什么会这样?为什么未检测到更改?
修改 以下是其他相关代码:
people.component.html
<tr class="person-row" *ngFor="let person of people">
<td class="name">{{person.name}}</td>
</tr>
people.service.ts
getPeople(): Observable<any> {
return this.http
.get(peopleUrl)
.map(response => response.json());
}
如果我在console.log(this.people)
内PeopleComponent.extractPeople()
,我正确地得到了一组人:
[
{
id: 11,
name: "John Smith"
},
...
]
但是,此时不会重新渲染组件。该视图仍显示人员数组的初始值为空。实际上,如果我用几个硬编码的人初始化数组,它们会在组件的初始渲染时正确显示。但是,当真正的http数据到达时,不会重新呈现此列表!就好像改变检测根本没有触发一样。
答案 0 :(得分:3)
我想你需要使用箭头功能来保留this
这一行:
this.peopleService.getPeople()
.subscribe(this.extractPeople); <=== here
这样您的代码应如下所示:
this.peopleService.getPeople()
.subscribe((res) => this.extractPeople(res));
有关使用箭头功能的更多信息,请访问https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this