Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable scope change in method called by map operator

Tags:

angular

rxjs

I was trying to change my data before returning it in the method called by map operator and i found out that all my other variable outside of that method are undefined

I wrote a simple code down here to represent what i mean, the logged test variable is returned as undefined:

import {Observable} from "rxjs/Observable";
import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";

@Injectable()
export class DataService {
    private API_URL= 'url...';
    private test = 1;

    constructor(private http: Http) {}

    getData(): Observable<any> {
        return this.http.get(this.API_URL)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        console.log(test);
        return body.data || {};
    }
}

I wanted to know why this is happening and if it's not the way to change fetched data how can i do it in the service (not in the subscriber component because i want to change data based on another variable that has nothing to do with subscriber component)

like image 735
Nima Hakimi Avatar asked Aug 22 '16 05:08

Nima Hakimi


People also ask

What is the purpose of the observable map operator?

The Map operator applies a function of your choosing to each item emitted by the source Observable, and returns an Observable that emits the results of these function applications.

What is map operator in RxJS?

The map operator in RxJS transforms values emitted from the source observable based on a provided projection function. This is similar to Array. map , except we are operating on each value emitted from an observable as it occurs rather than each value contained within an array.

What is the use of map operator in Angular?

The Angular observable Map operator takes an observable source as input. It applies a project function to each of the values emitted by the source observable and transforms it into a new value. It then emits the new value to the subscribers.

Which RxJS operators used for transforming or manipulating data?

Pipeable Operators and Creation Operators are the two kinds of operators in RxJS. The Pipeable Operators are methods that take an Observable as input and return another Observable. They can be piped to Observables using the syntax observableInstance. pipe(operator()) .


1 Answers

That's a JS "feature" ;-)

You need to use .bind(this)

    return this.http.get(this.API_URL)
        .map(this.extractData.bind(this))
        .catch(this.handleError.bind(this));

or arrow functions

    return this.http.get(this.API_URL)
        .map(val => this.extractData(val))
        .catch(err => this.handleError(err));

to retain the scope of this

like image 136
Günter Zöchbauer Avatar answered Nov 06 '22 10:11

Günter Zöchbauer