Dear Fellow Ionites
I’m trying to understand how to setup an HTTP data fetch service. I think I have done everything correctly but still I get an error
“Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.”
I have seen responses in similar problems, to mine but failed to understand what goes wrong with my code.
Let me explain:
I play around fetching JSON array from this link
http://jsonplaceholder.typicode.com/posts
If you put in browser you will see that it returns directly an array.
My code:
data-service.ts
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class DataService {
constructor (
private _http:Http
){}
getPosts():Observable<any>{
return this._http.get('http://jsonplaceholder.typicode.com/posts')
.map(res => res.json());
}
}
page1.html
<ion-navbar *navbar>
Tab 1
<ion-content padding class="page1">
<button (click)="getData()">Get Data</button>
<p>{{data}}</p>
<p *ngFor="let i of data">
{{i.id}}
</p>
</ion-content>
page1.ts
import {Page} from 'ionic-angular';
import {DataService} from '../../services/data-service/data-service';
@Page({
templateUrl: 'build/pages/page1/page1.html',
providers: [DataService]
})
export class Page1 {
data:any;
constructor(
private _data: DataService
) {
}
getData(){
this.data=this._data.getPosts()
.subscribe (
response => {
this.data=response;
console.log(this.data);
},
error => console.log ('error in download')
)
}
}
When I remove the *ngFor part from the HTML, and click on GetData the data are fetched. For a split second I see in my browser displayed [object Object], and then an array of [object Object]
If I put *ngFor part in my HTML, then I get the error:
“Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.”
I’m under the impression that the page does not see the returned data as array and thus ngFor throws the error. But in any case the console.log command shows that my data are indeed an Array of objects each time.
So I’m a bit confused. The data I get is an array (of course it’s a JSON but then it is converted in an array of objects). Yet my ngFor fails to work and throws an error.
Can some explain please? I’m totally confused. All these were based on tutorials I have found here and there, and yet they don’t seem to work. So I’m missing the best practice here.
Many thanks in advance.
Killerchip