Guerrilla
Guerrilla

Reputation: 14906

Custom mapping function for observable

I have an angular service that I want to return an object I have defined in an interface.

The tutorial I am following assumes that the response is identical to the interface but in my scenario I want to process the object a bit in order to just return some of the data.

My service method based on the tutorial is:

getResults(): Observable<IPageSpeedResult> {
        return this._http.get(this._pageSpeedApiUrl)
            .map((response: Response) => <IPageSpeedResult> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

How do I extend the map method to include my logic for building the IPageSpeedResult object from the returns data that I want? I basically need to access an array and then iterate over it to populate the return object.

Upvotes: 0

Views: 203

Answers (2)

Adnan A.
Adnan A.

Reputation: 1982

Well, you can do all of that inside the map operator.

getResults(): Observable<IPageSpeedResult> {
        return this._http.get(this._pageSpeedApiUrl)
            .map((response: Response) => <IPageSpeedResult> response.json())
            .map(data => this.transformData(data))
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

transformData(data: any) : IPageSpeedResult {
  // do your magic here
}

Upvotes: 3

Aravind
Aravind

Reputation: 41571

You can add your logic to either service method or when you subscribe the data, based on your business logics

getResults(): Observable<IPageSpeedResult> {
            return this._http.get(this._pageSpeedApiUrl)
                .map((response: Response) => <IPageSpeedResult> response.json())
                .do((data) => {
                        // your custom logic with the data

                })
                .catch(this.handleError);
    }

When subscribing to data

    this.serviceObject.getResults()
                      .subscribe((data)=>{
                        // your custom logic with the data
                      })

Note: It is not good practice to have the business logic in the services as they can be reused and construct a different set of data(some other custom mapping)

Upvotes: 2

Related Questions