2017-08-09 76 views
0

我從AngularJs 2應用程序調用WebAPI,API返回數據並將其分配給我的Angular組件的屬性,但是當我通過HTML使用此屬性時,它說出了undefiend。請幫助雖然在angularjs2中顯示數據超過html的錯誤

錯誤消息

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'BenefitId' of undefined 

下面是我benefit.component.ts代碼

import { Component, OnInit, ViewChild } from '@angular/core'; 
import { BenefitService } from '../services/benefit.service'; 
import { IBenefit } from '../models/benefit'; 

@Component({ 

    templateUrl: 'app/Components/benefit.component.html' 

}) 

export class BenefitComponent{ 

    constructor(private _benefitService: BenefitService) { } 

    benefits: any; 
    msg: string; 

    ngOnInit(): void { 
     this.LoadUsers(); 
    } 

    LoadUsers(): void { 
     this._benefitService.get("http://localhost/MyApi/api/Get/1950/7775/1") 
      .subscribe(benefits => { this.benefits = benefits; console.log(this.benefits); console.log('hi'); }, 
      error => this.msg = <any>error); 

    } 
} 

HTML代碼

<table> 
    <tr > 
     <td> 
      {{benefits.BenefitId}} 
     </td> 

    </tr> 
</table> 

回答

0

好處是undefined直到API返回的數據,當然你不能得到的財產。

所以,只要嘗試:

ngOnInit(): void { 
    this.benefits = {}; 
    this.LoadUsers(); 
} 
+0

我通過使用安全導航操作固定我的問題。 {{好處?.BenefitId}} – user2781180