首页 文章

数据更改时Angular2组件不呈现

提问于
浏览
1

我有一个非常简单的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 更新后,组件也不会重新渲染 . 为什么会这样?为什么未检测到更改?

Edit 以下是其他相关代码:

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

如果我 PeopleComponent.extractPeople()PeopleComponent.extractPeople() 内,我正确地得到了一组人:

[
    {
        id: 11,
        name: "John Smith"
    },
    ...
]

但是,此时不会重新呈现该组件 . 该视图仍显示人员数组的初始值为空 . 实际上,如果我用几个硬编码的人初始化数组,它们会在组件的初始渲染时正确显示 . 但是,当真正的http数据到达时,不会重新呈现此列表!就好像变化检测根本没有触发一样 .

1 回答

相关问题