アプリで奇妙なエラーが発生しています。{{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()
{{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();
}
}
何か案は?
ベストアンサー1
問題は、ページを初めてロードしたときにはthing
まだ未定義であり、後で非同期的に実際の値に設定されるため、初めてプロパティにアクセスしようとすると例外がスローされることです。elvis?
演算子は null チェックへのショートカットです。
{{thing?.title}}
ただし、通常は、次のようなコードを追加して実際のオブジェクトを取得するまでコンポーネントをレンダリングしない方がパフォーマンスが向上します。
<h1 *ngIf="thing">
コンテナに。