user39063
user39063

Reputation: 325

Fetching Array of Data from Backend with Angular 9

I need a little bit help with Angular (9). I do a GET Request to fetch a list of Users from the Backend:

    getUsers() {
    return this.http.get<User[]>(`${this._constant.baseAppUrl}/users/all`, )
        .pipe(map(user => {

            return user;
        }));
    }

My Goal is to get an Array of Objects with a type of the User Model. Instead I get an object.

enter image description here

I don't understand why. My IDE also shows, that the user variable is User[], but in the browser the typeof user is "object".

So how can I get an array back?

EDIT: This is the Answer from the Backend:

{
   "5ea04cfbcd595b393d78acbb": {
      "isAdmin": true,
      "role": "User",
      "status": "cEmail",
      "_id": "5ea04cfbcd595b393d78acbb",
      "name": "Test",
      "password": "$2b$10$re0gqblgXsfYus1mYA3yQ.Oiz4x81c3M2uxfE4tG6V7tNW1JMubXi",
      "email": "[email protected]",
      "__v": 0
   },
   "5ea1f308fc8909618668384e": {
      "isAdmin": true,
      "role": "User",
      "status": "cEmail",
      "_id": "5ea1f308fc8909618668384e",
      "name": "Mathias Braun",
      "password": "$2b$10$zpQezfiG4xNkwOTgV4CLIeYU4MITVfL2VhlLC3rqCbjBGl5TIpavG",
      "email": "[email protected]",
      "__v": 0
   }
}

Upvotes: 2

Views: 2142

Answers (1)

Sumit Kumar
Sumit Kumar

Reputation: 249

The backend is not returning the Array according to your provided JSON. But you can convert the object into the Array on the Angular side using the following way.

Modify your Api call function

getUsers():Observable<User[]> {
   return this.http.get<User[]>(`${this._constant.baseAppUrl}/users/all`, )
    .pipe(map(response=> {
       if(response){
          return Object.values(response); //This will return the array of object values.
        }
        return []; // If response is null return empty array for safety.
    }));
}

Now your getUsers() function will array of user object.

Upvotes: 1

Related Questions