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

非 Y 不嫁゛ 提交于 2019-11-28 08:22:16

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