Angular 4,将可观察到的HTTP响应转换为可观察到的对象

编程入门 行业动态 更新时间:2024-10-22 18:26:55
本文介绍了Angular 4,将可观察到的HTTP响应转换为可观察到的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对可观察对象的概念是新手,需要一些帮助来进行转换. 我有一个从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响应转换为可观察到的对象

本文发布于:2023-10-27 18:46:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:观察到   转换为   将可   对象   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!