简体   繁体   中英

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.

在此处输入图像描述

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": "dr@rootix.de",
      "__v": 0
   },
   "5ea1f308fc8909618668384e": {
      "isAdmin": true,
      "role": "User",
      "status": "cEmail",
      "_id": "5ea1f308fc8909618668384e",
      "name": "Mathias Braun",
      "password": "$2b$10$zpQezfiG4xNkwOTgV4CLIeYU4MITVfL2VhlLC3rqCbjBGl5TIpavG",
      "email": "mb@rootix.de",
      "__v": 0
   }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM