花了很长时间才弄清楚为什么会发生这种情况。我有一个使用CLI设置的A2项目,我有以下组件:
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-user-profile-card',
templateUrl: 'user-profile-card.component.html',
styleUrls: ['user-profile-card.component.scss']
})
export class UserProfileCardComponent implements OnInit {
public person;
constructor(private http: Http) {
}
getUserProfile(){
this.http.get('http://somedomain.com/12345')
.map(res => res.json())
.subscribe(
person => { this.person = person.person },
err => console.error(err),
() => console.log(this.person.sex)
);
}
ngOnInit() {
this.getUserProfile();
}
}
this.person.sex的控制台日志显示了正确的值,但是当我尝试从模板绑定到它时:
<div>{{ person.sex }}</div>
我得到以下错误:
undefined不是对象(求值'self.context.person.sex')
对此有什么想法吗?
这是因为所有http调用都是异步操作,并且您试图在数据到达之前在模板中显示person.sex
。你可以使用安全导航操作符 (?
)来"保护"你的模板,直到数据到达:
<div>
{{ person?.sex }}
</div>
也可以使用ngIf
指令:
<div *ngIf="person">
{{ person.sex }}
</div>
这样,在填充变量person
之前,div
不会出现在DOM中。你可以在这里阅读更多关于安全导航操作符的信息,在这里阅读更多关于ngIf
指令的信息。