arrays - Angular 为什么这个 HTTP 请求响应数组的长度未定义?

标签 arrays json angular typescript http

我正在尝试获取包含有关客户可以加入的大厅的信息的数据。我从 springboot API 获取这些数据。对于要在我的 Angular 前端中显示的数据,我将结果添加到作为组件属性的集合中。但是从 API 获取此数据并将其映射到对象数组后,我无法遍历结果。都是因为数组的长度被认为是未定义的。

我正在使用最新版本的 Angular(目前为 7)并且已经尝试使用 map 方法以不同方式映射 JSON 响应。而不是使用订阅功能。同样直接将响应分配给其他数组会出现此错误:LobbyComponent.html:10 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'。 NgFor 仅支持绑定(bind)到 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

最佳答案

您的 API 不返回数组,而是返回包含数组的对象。所以你应该

getLobbies(): Observable<Lobby[]> {
// find a neat name for T, it'll be an object containing a property `lobbies` of type Lobby[]
    return this.http.get<T>(this.apiURL+"/lobbies").pipe(
      tap(_ => this.log(`Got lobbies`)),
      catchError(/* error handling logic here */),
      map(({ lobbies }) => lobbies),
    );
  }

关于arrays - Angular 为什么这个 HTTP 请求响应数组的长度未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282418/

相关文章:

arrays - 从两个排序数组中找到第 k 个最小元素

python - 使用 Python 3 对数组进行排序

javascript - 在 Angular 7 中动态加载组件时出错。未找到组件工厂

node.js - api 响应包含转义字符

angular - 无法绑定(bind)到 'disabled',因为它不是 'li' 的已知属性

javascript - 将对象添加到数组对象

c - 二维数组 rand 函数乘法

arrays - 奇怪的行为:输入参数(具有以 “D”或 “L”字符结尾的多个值)

java - 阅读 Apache Spark 中的多行 JSON 文件后,如何获取嵌套属性作为列?

json - 如何在 F# 中对数学向量类型进行 JSON 序列化?