Angular 2:TypeError:l_thing0在AppComponent @ 4中的[{{thing.title}}中未定义:44]

Jos*_*osh 24 javascript typescript angular

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

EXCEPTION: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent@4:44]
Run Code Online (Sandbox Code Playgroud)

我不确定从哪里来l_thing0.如果我尝试{{thing}}在页面中显示,则会显示[object Object].如果我尝试JSON.stringify(this.thing)(参见该showObj()函数),它会正确显示字符串化对象.但是,如果我尝试访问属性,就像{{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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Lan*_*ley 52

问题是,第一次加载页面时,thing仍未定义,稍后将异步设置为其实际值,因此第一次尝试访问该属性时,它将引发异常.该?Elvis操作符是一个快捷方式nullcheck:

{{thing?.title}}

但它通常是一个最好的想法更高效甚至尝试渲染组件,直到你有真正的对象,通过添加如下:

<h1 *ngIf="thing">

到容器.