Observable with Angular 4 , NgFor only supports bi

2019-02-19 22:40发布

问题:

Yes, I see that other people get this error , I just don't quite get how to fix it in my code

private _url = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,LTC,EOS,DASH&tsyms=USD'

If I didn't have the return it does not crash with the error , but I do want to return the data.

I have a component that calls up this method ( in this service ts file )

Subscriber:

getAllCoins() {

    var blah = [];

    return this.getCoins().subscribe(
        data => {
            blah = data;               
            //console.log('subscriber coins', blah)
        }
    )

}

Calls this code

getCoins() {
    return this.http.get(this._url)
        .map((response: Response) => response.json())
        //.do(data => console.log(data))
        .do(data => console.log('All: ' + JSON.stringify(data)))  // do operator to peek 
        .catch(this.handleError);
}

Now, I see that the data from the url looks like this

{
"BTC": {
  "USD": 3349.1
},
"ETH": {
  "USD": 296.3
},
"LTC": {
  "USD": 47.56
},
"EOS": {
  "USD": 1.83
},
"DASH": {
  "USD": 195.83
}
}

How can I prevent from getting this error errors.ts:42 ERROR Error: Uncaught (in promise): Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

UPDATE for comment question

@Component({
template: `
<div>test</div>
<div *ngFor="let coin of coinsList">
 abc
 </div>
`
})

回答1:

As others have said, *ngFor only works on iterables.

There are a couple of methods that can be done to overcome this problem. Ones that come to my mind right now are:

1) You can push your list of objects to an Array.

this._ConfigurationService.getCoins()
            .subscribe(
            (data)=> {
                for(let key in data){
                  this.coinsList.push(data[key]);
                }
            },
            (error) => console.log("error : " + error)
        );

template:

<div *ngFor="let coin of coinsList">
    <span>{{coin | json}}</span>
</div>

Full plunker example: http://plnkr.co/edit/zrzVF8qKl8EvKKp2Qt45?p=preview

2) You can convert the response from object to an iterable using a pipe as shown in here: How to iterate [object object] using *ngFor in Angular 2

3) You can implement the iterable function to your object as shown here: Angular NgFor only supports binding to Iterables such as Arrays.

4) You can create special directive as shown here: Can ngForIn be used in angular 4?

My suggestion would be to use the first one for simplicity.



回答2:

As the erorr says you are trying to do a ngFor over Object, it works over any iterables.

Probably you can iterate over them and create an array, and then use it for the ngFor.