For instance, I'm currently calling unsubscribe from an Observable that is returned from Angular 2's HTTP module.
But I need to have some custom logic surrounding it.
Is it possible to add custom teardown logic to an already existing Observable, like the one returned from Angular 2's HTTP module?
Something along the lines of:
Observable.prototype.whenUnsubscribed(customTeardownLogic)
This might not be exactly what you want but it may help:
Suppose you have something like this (taken from the Hero Guide at Angular 2 website):
@Injectable()
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web API
constructor (private http: Http) {}
getHeroes(): Observable<Hero[]> {
return this.http
.get(this.heroesUrl)
.map(this.extractData);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
}
// Somewhere else in your code you do:
let subscription = service.getHeroes().subscribe(/* do stuff here */);
// ...and later on:
subscription.unsubscribe();
If you want to add some custom tear-down logic, you could wrap the Observable returned by Angular 2 with your own:
getHeroes(): Observable<Hero[]> {
return Observable.create(
//Let's provide a subscribe function
(observer: any) => {
const subscription = this.http
.get(this.heroesUrl)
.map(this.extractData)
.subscribe(observer);
// Return a tear-down/unsubscribe function
return () => {
subscription.unsubscribe();
this.myTearDownLogic();
}
}
);
}
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