Angular 2(TypeScript):无法从HTML模板中的http.get绑定到对象
花了一段很长的时间才弄明白为什么会发生这种事。我已经使用CLI设置了一个A2项目,我有以下组件:Angular 2(TypeScript):无法从HTML模板中的http.get绑定到对象,http,angular,typescript,get,angular2-template,Http,Angular,Typescript,Get,Angular2 Template,花了一段很长的时间才弄明白为什么会发生这种事。我已经使用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-
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>
{{person.sex}
我得到以下错误:
未定义不是对象(评估“self.context.person.sex”)
有什么想法吗?这是因为所有http调用都是异步操作,您试图在数据到达之前在模板中显示
person.sex
。您可以使用安全导航操作符(?
)来“保护”模板,直到数据到达:
<div>
{{ person?.sex }}
</div>
这样,在填充变量
person
之前,您的div
不会出现在DOM中。您可以阅读有关安全导航操作员的更多信息以及有关ngIf指令的更多信息。Wow。。。这么简单的事情,却产生了巨大的影响。我用了你的第一个例子,现在一切都很棒了。非常感谢!
<div *ngIf="person">
{{ person.sex }}
</div>