[Fixed] how do i loop through the response of an http request in angular 11

Issue

I am new to Angular, am using Angular 11, and having trouble doing an http request.
I have looked through pages of stack overflow posts and none have worked for me, even though some have similar questions.
I have an http request to a server to get json data, which the result comes back like this:

{
   "OleOleOle":3463,
   "Saitama":1,
   "SalsaMan":563,
   ...
}

I need to loop through the JSON and put each key value pair in an array as an object, with the key as the name and the value as the viewCount.

I have been trying to do it with this:

  getLiveStreams() {
    this.http.get<any>(this.server.url).subscribe(data => {
      console.log(data)
      data.forEach((stream: any) => console.log(stream))
    })
  }

But I get an error saying:

ERROR TypeError: data.forEach is not a function.

Solution

Your response is object try to use Object.keys(data).forEach((key: any) => console.log(key + ":" + data[key]))

Leave a Reply

(*) Required, Your email will not be published