簡體   English   中英

Angular 為什么這個 HTTP 請求響應數組的長度未定義?

[英]Angular Why is the length of this HTTP requests response Array undefined?

我正在嘗試獲取包含客戶可以加入的大廳信息的數據。 我從 springboot API 獲得這些數據。 對於要在我的 angular 前端中顯示的數據,我將結果添加到作為組件屬性的 Set 中。 但是在從 API 獲取這些數據並將其映射到 object 數組后,我無法遍歷結果。 這一切都是因為數組的長度據說是未定義的。

我正在使用最新版本的 Angular(當前為 7)並且已經嘗試過 map JSON 響應與 Z9518ZDC8ED512445 方法不同。 而不是使用訂閱 function。 直接將響應分配給另一個數組也會給出此錯誤:LobbyComponent.html:10 錯誤錯誤:找不到支持“對象”類型的 object“[對象對象]”的不同對象。 NgFor 僅支持綁定到 Iterables,例如 Arrays。

組件

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', []))
    );
  }

大廳 Class

export class Lobby{
    id: string;
    slots: User[]
}

JSON 結果來自 API

"lobbies": [
        {
            "users": null,
            "id": "Another Lobby!"
        },
        {
            "users": null,
            "id": "This is a Lobby!"
        }
    ]

我希望代碼循環遍歷結果並將它們添加到組件中的集合中。 但由於長度未定義,它不會遍歷響應元素。 並嘗試使用 forEach 而不是 for 循環會出現此錯誤: ERROR TypeError: response.forEach is not a function

您的 API 不返回數組,而是返回包含數組的 object。 所以你應該

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),
    );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM