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')

对此有什么想法吗?

那是因为所有 http 调用都是异步操作,并且您正试图在数据到达之前在您的模板中显示 person.sex。您可以使用 安全导航运算符 (?) "protect" 您的模板,直到数据到达:

<div>
    {{ person?.sex }}
</div>

你也可以使用ngIf指令:

<div *ngIf="person">
    {{ person.sex }}
</div>

这样,在填充变量 person 之前,您的 div 不会出现在 DOM 中。您可以阅读有关安全导航运算符的更多信息 here and more about ngIf directive here.