Angular2显示数据

时间:2017-03-07 11:21:01

标签: javascript html angular ionic2

我只是想通过服务显示我进入API的一些信息,但是当控制台向我显示我需要的信息时,我无法在我的视图中访问它。

我的角色服务

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)
            })
    })

  }

我的观看代码示例

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

错误代码

Cannot read property 'id' of undefined

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

2 个答案:

答案 0 :(得分:1)

这是因为Angular试图显示entreprise的属性,但尚未收到该对象。

有两种可能的解决方案:

  1. *ngIf="entreprise"内使用<div>,仅在entreprise不是null时显示内容。在<div>内,您可以安全地访问其所有属性(id,name ...)。在您的样本之后,它将是:

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

  2. 使用安全导航操作符(也称为 Elvis操作符),它由符号表示。这将阻止Angular 2将该属性移交给entreprise != undefined。要使用它,请按照您的示例进行操作:

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

  3. 希望它可以帮到你!

答案 1 :(得分:0)

*ngIf="entreprise"添加到div