【发布时间】:2020-02-05 12:12:20
【问题描述】:
我正在尝试获取包含客户可以加入的大厅信息的数据。我从 springboot API 获取这些数据。对于要在我的角度前端中显示的数据,我将结果添加到作为组件属性的 Set 中。但是在从 API 获取这些数据并将其映射到对象数组之后,我无法遍历结果。都是因为数组的长度据说是未定义的。
我正在使用最新版本的 Angular(当前为 7),并且已经尝试使用 map 方法以不同的方式映射 JSON 响应。而不是使用订阅功能。直接将响应分配给另一个数组也会产生此错误:LobbyComponent.html:10 错误错误:找不到类型为“object”的不同支持对象 '[object Object]'。 NgFor 只支持绑定到数组等 Iterables。
组件
export class LobbyComponent implements OnInit {
lobbies: Set<Lobby>;
constructor(private lobbyService: LobbyService) { }
getLobbies(): void {
this.lobbyService.getLobbies().subscribe(response => {
console.log(response);
// This solutions give this error: ERROR TypeError: response.forEach is not a function
// response.forEach(element => console.log(element.id))
//Todo: fix response.length is undifenided
console.log(response.length)
for (var i = 0; i < response.length; i++) {
console.log(i);
this.lobbies.add(response[i])
}
})
;
}
服务
getLobbies(): Observable<Lobby[]> {
return this.http.get<Lobby[]>(this.apiURL+"/lobbies").pipe(
tap(_ => this.log(`Got lobbies`)),
catchError(this.handleError<Lobby[]>('getLobbies', []))
);
}
大厅类
export class Lobby{
id: string;
slots: User[]
}
来自 API 的 JSON 结果
"lobbies": [
{
"users": null,
"id": "Another Lobby!"
},
{
"users": null,
"id": "This is a Lobby!"
}
]
我希望代码循环遍历结果并将它们添加到组件中的集合中。但由于长度未定义,它不会遍历响应元素。 并且尝试使用 forEach 而不是 for 循环会出现此错误:ERROR TypeError: response.forEach is not a function
【问题讨论】:
标签: arrays json angular typescript http