无法在Angular 2模板中显示对象的对象数组

时间:2017-04-23 23:55:45

标签: angular angular2-template

我正在尝试在角度2模板中显示对象值,特别是当我尝试使用ngFor获取对象数组时给出了一个错误说

EXCEPTION:未捕获(在承诺中):错误:./SgDetailComponent类中的错误SgDetailComponent - 内联模板:15:7导致:无法读取未定义的属性“标记” 我可以获取字符串/数字属性但不能获取对象属性。

这是我的component.ts

@Component({
  selector: 'app-sg-detail',
  templateUrl: './sg-detail.component.html',
  styleUrls: ['./sg-detail.component.scss', '../../app.component.scss']
})
export class SgDetailComponent implements OnInit {

  errorMessage: string;
  sgDetail: Sg;
  groupId: string;
  ipPermissions: IpPermissions[];
  userIdGroupPairs: UserIdGroupPairs[];
  opPermissionsEgress: IpPermissionsEgress[];
  tags: Tags[];

  constructor(private activatedRoute: ActivatedRoute, private sgService: SgService) { }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      let groupId = params['groupId'];
      this.groupId = groupId;
    });
    this.getSgsByGroupId(this.groupId);
  }
  getSgsByGroupId(groupId: String) {
    this.sgService.getSgByGroupId(groupId)
    .subscribe(
      sgDetail => this.sgDetail = sgDetail,
      error => {
        this.errorMessage = error.getMessage();
        console.error(error.getDescription());
      });
  }
}

这是我的component.html

 <div class="container app_container">
    <ul class="app_list">
        <li *ngIf="sgDetail" class="app_list-item">
            <p>GroupId: {{sgDetail.groupId}}</p>
            <p>GroupName: {{sgDetail.groupName}}</p>
        </li>
        <li *ngFor="let tag of sgDetail.tags" class="app_list-item">
             //this loop sgDetail.tags errors out 
        </li>
    </ul>
 </div>

这是我的model.ts

export interface Sg {
 ownerId: number;
 groupName: string;
 groupId: string;
 description: string;
 ipPermissions: IpPermissions[];
 ipPermissionsEgress: IpPermissionsEgress[];
 vpcId: string;
 tags: Tags[];
}

export interface IpPermissions {
 ipProtocol: string;
 fromPort: number;
 toPort: number;
 userIdGroupPairs: UserIdGroupPairs[];
 ipRanges: Array<number>;
 prefixListIds: Array<number>;
}

export interface UserIdGroupPairs {
 userId: number;
 groupName: string;
 groupId: string;
 vpcId: string;
 vpcPeeringConnectionId: string;
 peeringStatus: string;
}

export interface IpPermissionsEgress {
 ipProtocol: string;
 fromPort: number;
 toPort: number;
 userIdGroupPairs: UserIdGroupPairs[];
 ipRanges: Array<number>;
 prefixListIds: Array<number>;
}

export interface Tags {
 key: string;
 value: string;
}

2 个答案:

答案 0 :(得分:1)

错误是由Asynchorouse call - &gt;引起的。 getSgsByGroupId,这意味着当角度呈现视图时,getSgsByGroupId的结果尚未到来。

尝试角度提供的安全方式:

<li *ngFor="let tag of sgDetail?.tags" class="app_list-item">
</li>

答案 1 :(得分:-1)

试试这个: -

<ul *ngIf="let tag of sgDetail">
  <li>tag.groupId</li>
<ul>

But before looping or using *ngIf you should print sgDetail as a json like this:-
  {{sgDetail | json}}