angular unsubscribe in service needed code example
Example 1: angular unsubscribe example
import { Subscription, Observable } from 'rxjs';
import { OnDestroy } from '@angular/core';
export abstract class ComponentBase implements OnDestroy {
set subs(subscription: Subscription) {
this.subscriptioions.add(subscription);
}
private subscriptioions = new Subscription();
constructor() {};
subscribe(service: Observable<any>, successFn: (value: any) => void, errorHandler?: (value: any) => void) {
this.subs = service.subscribe(successFn, errorHandler || this.errorHandler);
}
ngOnDestroy() {
this.subscriptioions.unsubscribe();
}
private errorHandler(error) {
}
}
const product$ = this.productService.getProducts(productId);
this.subscribe(product$, (product) => {
})
Example 2: clean up an angular subscription
@Component({...})export class AppComponent implements OnInit { subscription: Subscription ngOnInit () { var observable = Rx.Observable.interval(1000); this.subscription = observable.subscribe(x => console.log(x)); }}