Angular 2 - Unable to display array


I’m pulling in a record from the database and trying to display the record without running it through *ngFor as its only one record returned.

I confirmed the data is returned by {{userDetails | json}}.
I can display the array via *ngFor but its just a record so there’s no need to loop through the record using *ngfor.
I tried {{userDetails.firstname}}, {{userDetails[0].firstname}}, and {{userDetails?.firstname}} nothing seems to be working.

what am i missing?

The funny thing is that the component script and the service script are basically a copy/past from one of my working script so im lost as to what is this I’m missing.

any help you can provide would be greatly appreciated

the error message received:

EXCEPTION: Uncaught (in promise): Error: Error in ../app/userporting/user-details.component.html:6:53 caused by: Cannot read property 'firstname' of undefined
Error: Error in ../app/userporting/user-details.component.html:6:53 caused by: Cannot read property 'firstname' of undefined

array format is:

[ { "firstname": "Mike", "lastname": "smith", "age": "29-Mar-78" } ]


		         .subscribe(data => this.userDetails = data); 


        return, getUserInfo, options )
                   .map((res: Response) => res.json())
                   .catch(error => <any>error);
1 Like

It looks like Angular is trying to render a template that references the properties of userDetails before the Ajax request has been made. You either need to initialize this.userDetails to an object with empty properties (i.e. { "firstname": "", "lastname": "", "age": "" }) or use ngIf to hide the part of the template that references it while it’s empty.


hi fretburner,

I used Array.isArray(this.userDetails); to determine if its an array and keep getting false. I was under the impression it was an array i was pulling in… no im bit confused as to whats coming through the service.

1 Like

If you’re getting an array back from the server, then probably the easiest thing to do is grab the first element when the result is returned:

  .subscribe(data => this.userDetails = data[0]);

Then in user-details.component.html you can do something like this:

<div *ngIf="userDetails">  
  <p>{{ userDetails.firstname }}</p>

Before the Ajax request is resolved, this.userDetails on the component will be undefined and so the ngIf directive will hide the part of the template that references the userDetails properties.


Thanks fretburner,
your instructions worked.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.