1

I have some problems to display an object in angular2

This is my Object which is an array of object and onother value)

enter image description here

That's how I retrieve it :

enter image description here

and that's how I try to display it in html

enter image description here enter image description here

  • The first question is how to display it?
  • The second question how to modify the "res.errorMessage[0]" to res only? (because I could have many objects in the res ...)

enter image description here

Thank you in advance.

amin89
  • 558
  • 1
  • 8
  • 26
  • what are you trying to do with `res.errorMessage[0]`, errorMessage is not an array (there is not even a `errorMessage` in your response). just `.map(res => res.json())` and access the error message like you have `{{result.errorMsg}}` – AT82 Apr 14 '17 at 08:59
  • Okay, now I saw that this object is apparently part of an array of the response? So how does your complete JSON look like? :) And PS, always add your code as code in your question, not pictures ;) – AT82 Apr 14 '17 at 09:03
  • that's right. it's a part of an array of the response (subscribe is done in the service.component). My object looks like that (see updated picture) PS : Ok good to know ;) – amin89 Apr 14 '17 at 09:06
  • now you could see the object like i receive it – amin89 Apr 14 '17 at 09:07
  • Possible duplicate of [TypeError: Cannot read property 'something' of undefined. Angular 2](http://stackoverflow.com/questions/41556213/typeerror-cannot-read-property-something-of-undefined-angular-2) – n00dl3 Apr 14 '17 at 09:35
  • @n00dl3 I would agree this is a dupe (was thinking of marking it myself), but this wouldn't really answer both of the OP's questions...? – AT82 Apr 14 '17 at 09:40
  • Glad to hear that someone did understand the second question :-D ! – n00dl3 Apr 14 '17 at 09:41

2 Answers2

2

In case you have several object, you'd want to extract the array from the response, like so:

.map(res => res.json().errorMessage)

Then you can iterate your result array and display the errorMsg:

<div *ngFor="let r of result"> {{r.errorMsg}}</div>

Demo

As to your first question, this is asynchronous, and you are pulling one object off the response. Since data retrieval is asynchronous, you are getting an undefined error, as your result-object is undefined at the point you are trying to display it in the template. This can be solved by using e.g the safe navigation operator:

{{result?.errorMsg}}

Here's more info: Cannot read property "totalPrice" of undefined

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167
1

Seems you get an observable from the async request as you are subscribing to it:

.map(res => res.json())
.subscribe(result => this.result = result.errorMessage[0]);  

Now {{result.errorMsg}} would print the message it holds.

Jai
  • 74,255
  • 12
  • 74
  • 103