how to unsubscribe from within the subscription angular obseravbles code example
Example 1: angular unsubscribe from observable
import { Subscription } from 'rxjs';
private searchEventSubscription: Subscription;
export class someComponent OnInit, OnDestroy {
constructor(private someService: SomeService) { }
ngOnInit() {
this.searchEventSubscription = this.someService.someMethod.subscribe(result => {
doSomething(result);
});
}
ngOnDestroy() {
this.searchEventSubscription.unsubscribe()
}
Example 2: 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) => {
})