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)
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.
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.
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.
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()) .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With