Angular2. HTTP http response to a specific instance of an object

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!

+4
source share
3 answers

, JSON ( , , ), , Object.

class MyClass {

  prop: number;

  static fromObject(src: Object) {
    var obj = new MyClass();
    obj.prop = src.prop;
    return obj;
  }
}

JSON MyClass:

Rx.Observable.of('[{"prop":1},{"prop":2},{"prop":3}]')
  .map(val => JSON.parse(val))
  .exhaustMap(val => new Rx.Observable.from(val))
  .map(val => MyClass.fromObject(val))
  .subscribe(
    item => console.log('Next: ', item),
    error => console.log('Error:', error),
    _ => console.log('Completed')
  );

:

  • .map(val => JSON.parse(val)) JSON, .

  • .exhaustMap(val => new Rx.Observable.from(val)) Observable exhaustMap , JSON .

  • .map(val => MyClass.fromObject(val)) map, MyClass.

-: http://jsfiddle.net/f5k9zdh1/1/

+2
.map((res: Response) => res.json().map(obj => new MyObject(obj.id, obj.name)))
+2

Try this syntax, you added it to your object:

 this.http.post(this.constants.taskUrl + parm, { headers: headers })
            .map((response: Response) => {
                var res = response.json();
                var result = <DataResponseObject>response.json();
                return result;
            })
0
source

Source: https://habr.com/ru/post/1654235/


All Articles