【问题标题】:Angular 2 (TypeScript): Unable to bind to object from http.get in HTML TemplateAngular 2(TypeScript):无法从 HTML 模板中的 http.get 绑定到对象
【发布时间】:2016-11-02 20:13:09
【问题描述】:

花时间弄清楚为什么会发生这种情况。我已经使用 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 angular typescript get angular2-template


    【解决方案1】:

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

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

    你也可以使用ngIf指令:

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

    这样,在填充变量 person 之前,您的 div 不会出现在 DOM 中。您可以阅读更多关于安全导航运算符here 和更多关于ngIf 指令here 的信息。

    【讨论】:

    • 哇...这么简单的事情,却产生了巨大的影响。我用了你的第一个例子,现在一切都很棒。非常感谢!
    猜你喜欢
    • 2017-09-04
    • 2016-10-07
    • 2017-09-20
    • 1970-01-01
    • 2016-10-17
    • 2016-12-29
    • 1970-01-01
    • 2016-12-23
    • 2016-05-03
    相关资源
    最近更新 更多