I have a problem with Angular, I'm trying to get data from my json with *ngFor but I get this error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
How can I go about solving it? Below is my code.
my service.ts
getChannels(): Observable<Channel[]> {
const url = this.urlGet;
return this.http.get<Channel[]>(url)
}
my component.ts
channels: Channel [] = [];
constructor(private channelService: ChannelService) { }
ngOnInit() {
this.getChannel();
}
getChannel() {
this.channelService.getChannels().subscribe(response => this.channels = response)
}
json from api
{
"result":
[
{
"id": 1,
"name": "Channel 1"
},
{
"id": 2,
"name": "Channel 2"
},
{
"id": 3,
"name": "Channel 3"
}
]
}
my component.html
<div *ngFor="let channel of channels">
{{channel.name}}
</div>
CodePudding user response:
Your getChannels function should look like this:
getChannel() {
this.channelService.getChannels().subscribe(response => this.channels = response.result)
}
You were assigning the whole object instead of the array inside.
In the future you should use the correct type for the returnvalue of the function with the http call:
getChannels(): Observable<{result:Channel[]}> {
const url = this.urlGet;
return this.http.get<{result:Channel[]}>(url)
}