2017-03-07 70 views
0

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

我的角服务

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

可能的重复[我无法在页面上获取JSON数据在Ionic 2插值后](http://stackoverflow.com/questions/42630452/im-unable-to-get-json-data-on - 插页后插入在离子-2) – echonax

+0

对象将是undefined请将* ngIf =“entreprise”添加到div –

回答

1

这是因为角度是试图展示企业公司的性质,尽管尚未收到的目标呢。

有两种可能的解决方案:

  1. 使用*ngIf="entreprise"<div>内,展示的内容只有entreprisenull。在<div>里面,你可以安全地访问它的所有属性(id,name ...)。按照你的样品,这将是:

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

  2. 使用安全导航操作(也称为猫王操作),它是由符号代表?。这将阻止Angular 2直到entreprise != undefined才会宣告propierty。要使用它,按照你的样品,这将是:

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

希望它可以帮助你!

+0

非常感谢你@ AMarquez94! * ngIf解决方案让我很困难,因为每一个绑定信息都被隐藏起来,甚至在页面加载时也不会出现。 但你让我学到了一些与猫王操作员有关的东西,它工作的很棒! 再次感谢。 – Nastyo

+0

不客气,我很高兴它帮助你! :) – AMarquez94

0

添加*ngIf="entreprise"div