Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  31] [ 6]  / answers: 1 / hits: 17305  / 9 Years ago, sat, january 16, 2016, 12:00:00

I'm getting a strange error in my app. It's supposed to print out {{thing.title}} from an object, but it shows an error in the console:



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


I'm not sure where l_thing0 is coming from. If I try to show {{thing}}in the page, it displays [object Object]. If I try to JSON.stringify(this.thing) (see the showObj() function), it correctly displays the stringified object. But if I try to access an attribute like {{thing.title}} I get the error that l_thing0 is undefined.



Here is 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();
}
}


Any ideas?


More From » angular

 Answers
4

The issue is that the first time you load the page, thing is still undefined, it gets set to its real value later on asyncronously, so the first time it tries to access the property, it will throw an exception. The ? elvis operator is a shortcut to a nullcheck:



{{thing?.title}}



But its usually a best idea more performant not even try to render the component at all until you have the real object by adding something like:



<h1 *ngIf=thing>



to the container.


[#63692] Friday, January 15, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
;