Angular 4, convert http response observable to object observable

后端 未结 3 628
没有蜡笔的小新
没有蜡笔的小新 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:34

    In the Angular 4+, It can be done automatically. You can change your getPriceTags method:

    export class PriceTagService {
        constructor(private http: HttpClient) {}
    
        getPriceTags<T>(): Observable<T> {
    
            // Set the request headers
            const headers = new Headers({ 'Content-Type': 'application/json' });
    
            // Returns the request observable
            return this.http.post<T>(`${Constants.WEBSERVICE_ADDRESS}/priceTag`, null, {headers: headers});
    
        }
    }
    

    And your DataSource class can be:

    export class PriceTagDataSource extends DataSource<PriceTag> {
        constructor (private priceTagService: PriceTagService) {
            super();
        }
    
        connect(): Observable<PriceTag> {
            // Here you can retrieve the Observable<PriceTag> from service and return directly
            return this.priceTagService.getPriceTags<PriceTag>();
        }
    
        disconnect() {}
    }
    
    0 讨论(0)
  • 2021-02-02 01:39

    As of angular 4.3 this can be done automatically.

    Example:

    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});

    Again, use the HttpClient instead of Http

    0 讨论(0)
  • 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<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()));
    
    }
    
    0 讨论(0)
提交回复
热议问题