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

Raf*_*ael 10 observable rxjs typescript angular

我是可观察的概念的新手,需要一些转换帮助.
我有一个服务Observable<Response>从Http请求返回一个,但我需要转换它做一个在connect方法内部Observable<PriceTag>使用它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});

}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

以下是我的请求回复的示例:

{
    // 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"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*hof 29

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

例:

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

    getSome(): Observable<MyAwesomeObject> {
        return this.http.get<MyAwesomeObject>('myUrl');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

再次,使用HttpClient而不是Http

  • 对我来说,这实际上并没有创建PriceTag对象.数据仍为Object类型. (3认同)

Bol*_*and 5

我猜你的 HTTP 响应是一个包含 PriceTag 的 JSON?问题是您要创建一个 PriceTag 对象。您可以通过类型转换将 json 转换为 PriceTag,但它不会是真正的 PriceTag 对象。

我们解决这个问题的方法是:

export class Serializable {
  constructor(json?: any) {
    if (json) {
      Object.assign(this, json);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后是一个可序列化的类:

export class PriceTag extends Serializable {}
Run Code Online (Sandbox Code Playgroud)

然后,您的 GetPriceTags 函数需要更改为:

getPriceTags(): Observable<PriceTag> {

    // 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})
    .map(res => new PriceTag(res.json()));

}
Run Code Online (Sandbox Code Playgroud)