Angular 4, convert http response observable to object observable

后端 未结 3 627
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 01:20

I\'m new to the concepts of observables and need some help with a conversion.
I have a service which returns an Observable from a Http request,

3条回答
  •  走了就别回头了
    2021-02-02 01:48

    I guess your HTTP Response is a JSON containing a PriceTag? The issue is that you want to create a PriceTag object. You can just convert the json to a PriceTag by type casting, but then it won't be a real PriceTag object.

    The way we have resolved this is:

    export class Serializable {
      constructor(json?: any) {
        if (json) {
          Object.assign(this, json);
        }
      }
    }
    

    And then a serializable class:

    export class PriceTag extends Serializable {}
    

    Then, your GetPriceTags function needs to be changed to:

    getPriceTags(): Observable {
    
        // 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()));
    
    }
    

提交回复
热议问题