0

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>

1 Answer 1

2

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)
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.