嵌套对象绑定成角度的问题

时间:2018-08-01 10:47:21

标签: angular

在我绑定一个嵌套模型以查看的角度6中,它给出的错误为“无法读取未定义的属性”。

模型-

    export class Country {
    CountryID: number;
    CountryCode: string;
    CountryName: string;
    CurrencyCode: string;
}

export class Data {
    Country: Country[]
}

export class CountryMaster {
    IsSuccess: boolean;
    ErrorCode: string;
    ErrorDescription: string;
    Data: Data;
}

组件

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CountryMaster, Country,Data } from '../Shared/Model/CountryModel';

@Component({
  selector: 'app-shopping',
  templateUrl: './shopping.component.html',
  styleUrls: ['./shopping.component.css']
})
export class ShoppingComponent implements OnInit {

  constructor(public httpCl: HttpClient) { }
  ListOfCountry: Data;
  countries: Country[];

  ngOnInit() {
    this.BindCountry();
  }

  BindCountry(): void {


  this.httpCl.get("http://localhost:59049/api/Country/GetCountry").subscribe(
      (successData: CountryMaster) => {
        this.ListOfCountry = successData.Data;
      },failData => {
        //alert(failData);        
      });
  }
}

和模板

  <div *ngFor="let ctry of ListOfCountry.Country">
  <div>
    <label>{{ctry.CountryCode}}</label>
    <label>{{ctry.CountryName}}</label>
  </div>
</div>

尽管它绑定数据,但也会在控制台中显示错误。当我通过国家模型列表进行查看时,它可以正常工作,或者当我添加条件*ngIf="ListOfCountry"时,则没有错误。任何人都可以帮助我为什么当我与嵌套对象绑定时发生这种情况

error

2 个答案:

答案 0 :(得分:1)

在渲染视图后收到您的数据响应的情况下,可能会发生这种情况。

尽管已在ngOnInit()中调用了该API,但取决于您的API响应时间,数据可能会在视图渲染后到达。

在这种情况下,ListOfCountry: Data;没有Data对象类型的定义。它只是声明的,没有定义的。因此,它无法在其中找到Country对象。

您可以声明以下对象来忽略此条件:

ListOfCountry: Data = { Country = [] };

答案 1 :(得分:0)

尝试使用安全的导航操作员吗?

div *ngFor="let ctry of ListOfCountry?.Country">
  <div>
    <label>{{ctry?.CountryCode}}</label>
    <label>{{ctry?.CountryName}}</label>
  </div>
</div>