在angularjs2中通过html显示数据时出错

时间:2022-06-22 19:44:56

i am calling WebAPI from AngularJs 2 app, API return data and i assinging it to property of my Angular component but when i using this property over HTML its saying undefiend. Please help

我从AngularJs 2应用程序调用WebAPI,API返回数据,并且我将它分配给我的Angular组件的属性但是当我使用这个属性而不是HTML时,它说的是undefiend。请帮忙

Error message

错误信息

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

Below is my benefit.component.ts code

下面是我的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 code

HTML代码

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

    </tr>
</table>

1 个解决方案

#1


0  

benefits is undefined till API returns a data, and of course you can't get property BenefitId of undefined.

在API返回数据之前,好处是未定义的,当然,您无法获得未定义的属性BenefitId。

So, just try:

所以,试试吧:

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

#1


0  

benefits is undefined till API returns a data, and of course you can't get property BenefitId of undefined.

在API返回数据之前,好处是未定义的,当然,您无法获得未定义的属性BenefitId。

So, just try:

所以,试试吧:

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