I'm getting this error while retrieving the array of users: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
The request function on the service:
getUsers(): Observable<any[]> {
return this.http.get<any[]>('http://localhost:3000/users')
.pipe(map((res: any) => {
return res;
}))
}
The html component:
<tr *ngFor="let user of userData">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.password}}</td>
The TS component:
getAllUsers(){
this.accountService.getUsers()
.subscribe(res=>{
console.log('getallusers novo',res);
this.userData = res;
},
err=>{
console.log(err);
alert('faio');
})
}
I want to fetch the users from the URL, when I do the request on Postman it's OK. Postman
CodePudding user response:
Change it to this :
getUsers(): Observable<any[]> {
return this.http.get<any[]>('http://localhost:3000/users')
.pipe(map((res: any) => {
return res.users;
}))
CodePudding user response:
The error [object Object] say that you try to do a loop with a OBJECT.
You need converter this OBJECT in ARRAY.
You can do three options:
- In the api, answer with a ARRAY
- In the frontend, execute this processes a convert the OBJECT in ARRAY:
https://www.javascripttutorial.net/object/convert-an-object-to-an-array-in-javascript/
- Do this in getAllUsers():
this.userData = res.users;
(res.users is a ARRAY)