微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 4,将http响应observable转换为object observable

我是可观察的概念的新手,需要一些转换帮助.
我有一个服务,它返回一个Observable< Response>从一个Http请求,但我需要转换它做一个Observable< PriceTag>在connect方法中的DataSource上使用它.
反正有没有这样做?

这是我服务的方法

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>.get('myUrl');
    }
}

所以在你的情况下,这将是:

返回this.http.post< PriceTag>(Constants.WEBSERVICE_ADDRESS“/ priceTag”,{headers:headers});

再次,使用HttpClient而不是Http

原文地址:https://www.jb51.cc/angularjs/141724.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐