Angular 2:TypeError:l_thing0在AppComponent @ 4:44的

我在我的应用程序中遇到了一个奇怪的错误。 它应该从对象中打印{{thing.title}} ,但是在控制台中显示错误:

 EXCEPTION: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent@4:44] 

我不确定l_thing0是从哪里来的。 如果我尝试在页面中显示{{thing}} ,则会显示[object Object] 。 如果我尝试JSON.stringify(this.thing) (请参阅showObj()函数),它正确显示string化的对象。 但是,如果我尝试访问像{{thing.title}}这样的属性,我会得到l_thing0未定义的错误。

这里是app.component.ts:

 import {Component, OnInit} from 'angular2/core'; import {Thing} from './thing'; import {ThingService} from './thing.service'; import {SubThingComponent} from "./subthing.component"; @Component({ selector: 'thing-app', template: ` <div class="container"> <div class="row"> <div class="col-md-12"> <h1>{{thing.title}} <a href="#" (click)="showObj()" class="btn btn-default">Show Stringified Obj</a></h1> <subthing></subthing> </div> </div> </div> `, styles:[` `], directives: [SubThingComponent], providers: [ThingService] }) export class AppComponent implements OnInit { constructor(private _thingService: ThingService) { } public thing: Thing; showObj() { // This correctly shows the stringified object alert(JSON.stringify(this.thing)); } getThing() { this._thingService.getThing().then(thing => this.thing = thing); // This correctly logs the object setTimeout(() => {console.log('thing', this.thing)}, 5000); } ngOnInit() { this.getThing(); } } 

有任何想法吗?

问题是,第一次加载页面时, thing仍然是未定义的,后来被asynchronous设置为真实值,所以第一次尝试访问该属性时,会抛出exception。 这个? elvis操作符是一个nullcheck的快捷方式:

{{thing?.title}}

但是,它通常是一个更好的performance,甚至不尝试渲染组件,直到你有了真实的对象,像这样:

<h1 *ngIf="thing">

到容器。