简体   繁体   中英

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

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!

*ngIf="entreprise"添加到div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM