I have the following code that returns an observable, it checks if the this.data is valid JSON, otherwise it tries to fetch it from url. The fetching and everything works.
load():Observable<IStandardListOutput[]> {
return Observable.create(observer => {
if (this.needsFetch) {
var data;
this.http.get(this.data)
.map(res => {
var result = res.text();
// console.log(result);
try {
data = JSON.parse(result)
} catch (e) {
return Observable.of([{error:"ERROR LOADING JSON: " + this.data}]);
}
return data;
}).subscribe(res => {
observer.next(this._parse(res));
observer.complete();
});
}else {
observer.next(this._parse(this.data));
observer.complete();
}
});
}
Now in the map/subscribe portion of the observer I have the following:
let observable$ = this.loader.load(); // <-- load method above
observable$.map(res => {
console.warn ("IN MAP: " + JSON.stringify(res));
});
observable$.subscribe(res=> {
console.log("IN SUB: " + JSON.stringify(res));
},
err => {
console.log(JSON.stringify(err))
},
() => {
console.info("COMPLETE")
}
);
What I see in the output/console is only the "IN SUB" (subscribe) function and a "COMPLETE". The console.warn in the .map function is never executed.
Any help is highly appreciated, thanks in advance
The map is never executed because it creates an observable that stays cold (no subscription).
Add an empty subscribe()
and it should work.
observable$.map(res => {
console.warn ("IN MAP: " + JSON.stringify(res));
}).subscribe();
And another tip on rxjs debugging, if you want to peek into the value, you can always use the do
operator (instead of your map
).
observable$
.do((v) => console.log('debug point: ', v)) // <-- this is the addition.
.subscribe(...your original handlers go here ...)
rxjs changed a lot. Angular 2 (8) is very different from AngularJS.
Since version 6 from rxjs, you need to import it with
import {map} from 'rxjs/operators';
and, in your code, include it with a pipe
, for example:
observable.pipe(map(res => res.json()).subscribe( {
console.log("IN SUB: " + JSON.stringify(res)); },
err => {
console.log(JSON.stringify(err))},
() => {
console.info("COMPLETE")
}
hope this helps!
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