Angular2 RxJS class call function from display function

I am new to Angular 2 and Observables, so I apologize if my problem is trivial. Anyway, I'm trying to test the Angular 2 HTTP client using RxJS. Although I got it to work, I need to add more logic to the service I'm currently working on. Basically, I would like to have a mapping function to transform the object received from the web service that I am connected to to the model object that I have in Angular.

This is the code that works:

import { Injectable } from 'angular2/core'; import { Http, Response } from 'angular2/http'; import { Observable } from 'rxjs/Observable'; import { Person } from '../models/person'; @Injectable() export class PersonsService { constructor(private http: Http) { } private personsUrl = 'http://localhost/api/persons'; getPersons(): Observable<Person[]> { return this.http.get(this.personsUrl) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { if(res.status < 200 || res.status >= 300) { throw new Error('Bad response status ' + res.status); } let body = res.json(); return body.data || {}; } private handleError(error: any) { let errMsg = error.message; return Observable.throw(errMsg); } } 

I have no problem with the code above. The problem I am facing is that I would like to map the object that I get from the service to the one that I have in Angular ie Person . I tried calling another function from the extractData function, which is used by the .map function.

 private extractData(res: Response) { if(res.status < 200 || res.status >= 300) { throw new Error('Bad response status ' + res.status); } let body = res.json(); // map data function var data = this.mapData(body.data); return data || {}; } private mapData(data: any) { // code to map data } 

Obviously, the above code does not work when this referenced inside the extractData function, this does not belong to the PersonsService class, but refers to the MapSubscriber object.

I do not know if an "external" function can be called. It may be stupid, but I can not find any information about it.

+5
source share
2 answers

Instead of just using the function reference, use arrow functions to save this

 .map((res) => this.extractData(res)) 
+17
source

In fact, the Observed Map Function allows you to pass a reference variable as a second argument about how this really works inside a higher-order function.
so the solution is .map(this.extractData,this)
Thus, by passing the extractData function, you also pass the current execution context of this to a higher-order function. He will work.

Link to the watched document link

document screenshot </ a

+2
source

All Articles