Nastyo
Nastyo

Reputation: 199

Angular2 Display data

I am just trying to display some information that I get into my API by a service but, I can't access to it in my view while the console show me the info that I need.

my angular service

getById(id){

    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.get(this.urlRoot+'entreprise/'+id, {headers:headers})
            .subscribe(res=>{
                let data = res.json();
                resolve(data.entreprise);
            }, (err) =>{
                reject(err)
            })
    })

  }

my view code sample

<div class="entreprise-name"><h1> {{ entreprise.name }} </h1></div>

the error code

Cannot read property 'id' of undefined

the API json answere

{
  "entreprise": {
    "id": 1,
    "domaine_id": 1,
    "category_id": 1,
    "name": "Culry Hairs",
    "location": "Rue du Travail 1, 7000 Mons, Belgium",
    "description": "La coupe qui décoiffe",
    "contact_person": "Marie Kristy",
    "phone_number": "065/53.46.55",
    "createdAt": "2017-03-05T23:00:00.000Z",
    "updatedAt": "2017-03-05T23:00:00.000Z"
  }
}

img of the 'console.log' of the data

Upvotes: 0

Views: 82

Answers (2)

AMarquez94
AMarquez94

Reputation: 277

That is because Angular is trying to show the properties of entreprise, while it has not received the object yet.

There are two possible solutions:

  1. Use *ngIf="entreprise" inside the <div>, to show the content only if entreprise is not null. Inside the <div> then you can access safely to all its properties (id, name...). Following your sample, it would be:

    <div class="entreprise-name" *ngIf="entreprise"><h1> {{ entreprise.name }} </h1></div>

  2. Use the safe navigation operator (also called Elvis operator), and it is represented by symbol ?. This will prevent Angular 2 to rending the propierty until entreprise != undefined. To use it, following your sample, it would be:

    <div class="entreprise-name"><h1> {{ entreprise?.name }} </h1></div>

Hope it helps you!

Upvotes: 1

Babar Hussain
Babar Hussain

Reputation: 2915

add *ngIf="entreprise" to the div

Upvotes: 0

Related Questions