Angular 2 (TypeScript):无法绑定到 HTML 模板中 http.get 的对象
Angular 2 (TypeScript): Unable to bind to object from http.get in HTML 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-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 is not an object (evaluating 'self.context.person.sex')
对此有什么想法吗?
费了好大劲才弄清楚为什么会这样。我已经使用 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 is not an object (evaluating 'self.context.person.sex')
对此有什么想法吗?