问题描述
我试图了解如何使用Angular 2中的http.get和Observables将服务调用的结果映射到对象.
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.
看看这个 Plunk
在方法getPersonWithGetProperty中,我希望返回一个PersonWithGetProperty类型的Observable.然而!我无法访问属性fullName.我猜想我将不得不创建类PersonWithGetProperty的新实例,并使用类构造函数将响应映射到该新对象.但是,您如何在getPersonWithGetProperty方法中做到这一点?
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()));
}
}
推荐答案
问题是您正在强迫解析的json表现得像类.
The problem is that you are coercing the parsed json to behave like the class.
应用<PersonWithGetProperty>
实际上并没有创建PersonWithGetProperty
的新实例,它只是告诉编译器关闭,因为您知道自己在做什么.如果要实际创建实例PersonWithGetProperty
,则需要使用new
构造它.
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
.
幸运的是,您已经到了一半,只需在解析输出之后再添加一个map
:
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));
}
}
修改
为此,您需要确保您正在使用RxJS 5:
For this to work you will need to make sure you are using for RxJS 5:
import 'rxjs/add/operator/map'
如果您想要将来的安全,则应该使用RxJS 5更高版本中引入的pipe
语法
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))
);
这篇关于如何将响应从http.get映射到Angular 2中类型对象的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!