【发布时间】:2017-09-20 12:39:22
【问题描述】:
我正在尝试在 Angular 2 模板中显示对象值,特别是当我尝试使用 ngFor 获取对象数组时,会出现错误提示
异常:未捕获(承诺中):错误:./SgDetailComponent 类 SgDetailComponent 中的错误 - 内联模板:15:7 原因:无法读取未定义的属性“标签” 我可以获取字符串/数字属性,但不能获取对象属性。
这是我的组件.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());
});
}
}
这是我的组件.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;
}
【问题讨论】:
-
我认为当您使用
let sgDetail of sgDetail.tags时,您正在重新分配sgDetail,从而丢失您在组件上设置的属性的引用。尝试使用其他名称,例如let tag of sgDetail.tags -
@AlexandreAngelim 仍然不起作用。我认为错误是在尝试获取 tags 属性时出现的。
-
我看不出有什么问题。稍微调试一下怎么样? console.log sgDetail 刚刚分配到
getSgsByGroupId。