我对可观察对象的概念是新手,需要一些帮助来进行转换. 我有一个从Http请求返回Observable<Response>的服务,但我需要将其转换为Observable<PriceTag>才能在connect方法内的DataSource上使用它. 反正有这样做吗?
I'm new to the concepts of observables and need some help with a conversion. I have a service which returns an Observable<Response> from a Http request, but I need to convert it do an Observable<PriceTag> to use it on a DataSource inside the connect method. Is there anyway to do this?
这是我服务中的方法:
getPriceTags(): Observable<Response> { // Set the request headers const headers = new Headers({ 'Content-Type': 'application/json' }); // Returns the request observable return this.http.post(Constants.WEBSERVICE_ADDRESS + "/priceTag", null, {headers: headers}); }这是DataSource类,在这里我需要将其作为Observable<PriceTag>返回:
And here is the DataSource class where I need to return it as an Observable<PriceTag>:
export class PriceTagDataSource extends DataSource<PriceTag> { constructor (private priceTagService: PriceTagService) { super(); } connect(): Observable<PriceTag> { // Here I retrieve the Observable<Response> from my service const respObs = this.priceTagService.getPriceTags(); // Now I need to return a Observable<PriceTag> } disconnect() {} }以下是我的请求响应中的一个示例:
Here's an example from the response from my request:
{ // This object is used to check if the query on the server was sucessful "query": { "sucessful": true }, // These are my PriceTags "tags": [ { "id": "1", "name": "MAIN" }, { "id": "2", "name": "CARD" } ] }推荐答案
从angular 4.3开始,这可以自动完成.
As of angular 4.3 this can be done automatically.
示例:
export class SomeService { constructor(private http: HttpClient) {} // <--- NOTE: HttpClient instead of Http getSome(): Observable<MyAwesomeObject> { return this.http.get<MyAwesomeObject>('myUrl'); } }因此,您的情况应该是:
So in your case that would be:
return this.http.post<PriceTag>(Constants.WEBSERVICE_ADDRESS + "/priceTag", null, {headers: headers});
同样,使用HttpClient代替Http
更多推荐
Angular 4,将可观察到的HTTP响应转换为可观察到的对象
发布评论