How to map a response from http.get to a new instance of a typed object in Angular 2 [duplicate]

只谈情不闲聊 提交于 2019-11-27 01:51:54

问题


I'm trying to get an understanding in how to map the result from a service call to an object using http.get and Observables in Angular 2.

Take a look at this Plunk

In the method getPersonWithGetProperty I'm expecting to return an Observable of type PersonWithGetProperty. However! I can't access the property fullName. I guess that I would have to create a new instance of the class PersonWithGetProperty and map the response to this new object using the class constructor. But how do you do that in the method getPersonWithGetProperty?

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

export class PersonWithGetProperty {
  constructor(public firstName: string, public lastName: string){}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => <PersonWithGetProperty>(response.json()));
    }
}

回答1:


The problem is that you are coercing the parsed json to behave like the class.

Applying the <PersonWithGetProperty> isn't actually creating a new instance of PersonWithGetProperty it is just telling the compiler to shut up because you know what you are doing. If you want to actually create an instance PersonWithGetProperty you need to construct it with new.

Fortunately you are already half way there, just add another map after you have parsed the output:

@Injectable()
export class PersonService {
    constructor(private http: Http) {
    }

    getPersonWithGetProperty(): Observable<PersonWithGetProperty> {
        return this.http.get('data/person.json')
         .map((response: Response) => response.json())
         .map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName));
    }
}

Edit

For this to work you will need to make sure you are using for RxJS 5:

import 'rxjs/add/operator/map'

If you want future safety you should be using the pipe syntax introduced in later versions of RxJS 5

// Either
import {map} from 'rxjs/operators'

return this.http.get('data/person.json').pipe(
  map((response: Response) => response.json()),
  map(({firstName, lastName}) => new PersonWithGetProperty(firstName, lastName))
);


来源:https://stackoverflow.com/questions/37310511/how-to-map-a-response-from-http-get-to-a-new-instance-of-a-typed-object-in-angul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!