Angular为什么此HTTP请求响应数组的长度未定义?

时间:2019-10-08 08:07:01

标签: arrays json angular typescript http

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

我正在使用最新版本的Angular(当前为7),并且已经尝试使用map方法以不同的方式映射JSON响应。而不是使用订阅功能。同样直接将响应分配给另一个数组也会出现此错误:LobbyComponent.html:10错误错误:找不到类型为'object'的其他支持对象'[object Object]'。 NgFor仅支持绑定到数组等Iterable。

组件

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循环会出现此错误:错误TypeError:response.forEach不是函数

1 个答案:

答案 0 :(得分:5)

您的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),
    );
  }
相关问题