角度4,将http响应可观察到的转换为可观察对象

拉斐尔

我是可观察对象的新手,需要一些帮助来进行转换。
我有一个Observable<Response>从Http请求返回an的服务,但是我需要对其进行转换Observable<PriceTag>DataSource在connect方法内部使用它
反正有这样做吗?

这是我服务的方法:

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>

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() {}

}

这是我的请求响应中的一个示例:

{
    // 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"
        }
    ]
}
罗宾·迪克霍夫

从角度4.3开始,这可以自动完成。

例:

export class SomeService {
    constructor(private http: HttpClient) {}  // <--- NOTE: HttpClient instead of Http

    getSome(): Observable<MyAwesomeObject> {
        return this.http.get<MyAwesomeObject>('myUrl');
    }
}

因此,在您的情况下,将是:

return this.http.post<PriceTag>(Constants.WEBSERVICE_ADDRESS + "/priceTag", null, {headers: headers});

同样,使用HttpClient代替Http

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章