Reputation: 227
I am using angular 10 for my application. in my application, I have a get method and I got the data i want to display it. for this question there are lot of answers are there in here, but i tried everything it doesn't work properly.
I have a model file and in that file, I have deserialize(), serialize() options also, so the response data type should same as the interface file type. But response data showing this error(Only arrays and iterables are allowed)not rendering in HTML also. but I used an empty array for the response data variable.
I included my stackblitz URL also here, please help me to fix this.
This is my model.ts codes:
userInfo: userInformation[] = [];
ngOnInit() {
this.enableLoader = true;
this.formService.findAll().subscribe((data: userInformation[]) => {
this.enableLoader = false;
this.userInfo = data;
console.log(this.userInfo)
});
This is my mode.ts file
export class userInformation extends Base implements PageObject {
@serializable
public id: number;
@serializable
public avatar: string;
@serializable
public email: string;
@serializable(alias('first_name'))
public firstname: string;
@serializable(alias('last_name'))
public lastname: string;
deserialize(input: any): this {
return Object.assign(this, deserialize(userInformation, input));
}
}
This is my service file:
public findAll():Observable<userInformation[]> {
return this.httpClient.get<userInformation[]>(this.usersUrl + '/api' + '/users' + '?page=2', {
headers: this.httpHeaders.contentTypeApplication,
params: this.httpHeaders.serializeParams()
})
}
Upvotes: 0
Views: 3410
Reputation: 4228
Result of your console.log :
data: Array[6]
page: 2
per_page: 6
support: Object
total: 12
total_pages: 2
If you look at the log into your devtools generated by your console.log(this.userInfo)
, it doesn't log an array of type userInformation[]
. This array is nested into the data
property of the response.
As the response is an object, you get an error explaining you cant iterate over it (as you can't iterate on the object).
You need to change the data returned by your service to map it to the data property.
You need a new interface to match the response of the api :
interface UsersResponse {
data: userInformation[];
page: number;
per_page: number;
support: any;
total: number;
total_pages: number;
}
Then you need to update the returned type of your http call and add the rxjs map operator to change the stream to the data property :
public findAll():Observable<userInformation[]> {
return this.httpClient.get<UsersResponse>(this.usersUrl + '/api' + '/users' + '?page=2', {
headers: this.httpHeaders.contentTypeApplication,
params: this.httpHeaders.serializeParams()
}).pipe(
map(response => response.data)
);
}
Last step, update your template from :
<div class="wrapper" *ngFor="let users of userInfo?.data">
to
<div class="wrapper" *ngFor="let users of userInfo">
Upvotes: 1