The general approach to handling an HTTP response is as follows:
return this._http.get(url)
.map((res: Response) => res.json());
which provides you Observable<Object[]>with where Objectthe dynamically generated type is from json de-serialization. Then you can use this result in *ngFor="let item of result | async"etc.
I would like to get an instance of a specific type (which means using an operator newto call the type constructor). Tried different ways to achieve something like this:
.map((res: Response) => { let obj = res.json(); return new MyObject(obj.id, obj.name);})
but getting this error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
This method seems to work, but it is too complicated and probably inefficient:
.map((res: Response) => {
let results = <MyObject[]>[];
let obj = res.json();
obj.forEach(
function (o: any) {
results.push(new MyObject(o.id, o.name));
}
);
return results;
}
Thank!
rook source
share