好的,我有这个组件,并且正在迭代数据。没有切片管一切都很棒。当我添加切片管道来限制输出时,事情会发生不同的变化。 Angular 发送此错误 Object is of type 'unknown'.ngtsc(2571) 上
这是 API 上的数据存储。它像这样作为一个对象返回
{
"generated_at": "-",
"schema": "-",
"event": {
"id": "-",
"scheduled": "-",
"value": false,
"timing": {
"type": "-",
},
"season": {
"id": "-",
"name": "-",
"start_date": "-",
"end_date": "-",
"year": "-",
},
"cycle": {
"id": "",
"name": "-",
"car": {
"id": "-",
"name": "-"
},
"category": {
"id": "-",
"name": "-"
},
"type": "-",
"value": "-"
},
"useful": [{
"id": "-",
"name": "-",
"value": "-",
"value2": "-",
"value3": "-",
"value4": "-"
}, {
"id": "-",
"name": "-",
"value1": "-",
"value2": "-",
"value3": "-",
"value4": "-"
}],
"venue": {
"id": "-",
"name": "-",
"city_name": "-",
"country_name": "-",
"map_coordinates": "--",
"country_code": "-",
"values": [{
"name": "-"
}, {
"name": "-"
}]
}
},
"section": [{
"locale": "-",
"value": {
"id": "-",
"name": "-",
"country_code": "-"
},
"street_group": [{
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}
]
}, {
"locale": "-",
"value": {
"id": "-",
"name": "-",
"country_code": "-"
},
"street_group": [{
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}, {
"id": "-",
"name": "-",
"type": "-",
}
]
}]
}
这是组件,其中.get数据,然后将数据推送到数组,使其成为可迭代。
export class LiveComponent implements OnInit {
allData: any = null;
constructor(private http: HttpClient ) {
}
ngOnInit(){
this.http.get('http://api.redacted_for_privacy').subscribe(data => {this.allData = [data];});
}
}
只要我不使用切片管道,这就是迭代工作的 HTML。
错误发生在{{street_group.name}},其中 Angular 表示对象的类型为“未知”。
<mat-tab-group>
<mat-tab *ngFor="let data of allData" label="{{data.event.useful[0].name}}">
>! The part below is broken
<div class="content">
<mat-list role="list" *ngFor="let section of data.section">
<mat-list-item role="listitem" *ngFor="let street_group of section.street_group | slice:0:10">{{street_group.name}}</mat-list-item>
</mat-list>
</div>
</mat-tab>
</mat-tab-group>
我想使用切片管道将结果限制为 street_group 中的 7 个项目,因为 2 个不同的对象中有 14. 7 个项目。但 Angular 在两个对象中都打印了整个 14。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
奇怪的是,你会得到这个错误,因为 allData 的类型是
any因此所有嵌套字段都是unknown为了解决这个问题,只需添加如下内容:
// component.ts allData: { generated_at: string; section: { street_group: { name: string }[]; locale: string }[]; event: { id: string; useful: { name: string }[]; }; }[] = [];另请注意,初始值应设置为
[]。否则,输入应该像这样:// component.ts allData: { generated_at: string; section: { street_group: { name: string }[]; locale: string }[]; event: { id: string; useful: { name: string }[]; }; }[] | null = null;