angular observable unsubscribe 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) => {
})
Example 3: 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)); }}
Example 4: how to unsubscribe from observable created by http
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
interface User {
id: string;
name: string;
age: number;
}
@Component({
selector: 'app-foobar',
templateUrl: './foobar.component.html',
styleUrls: ['./foobar.component.scss'],
})
export class FoobarComponent implements OnInit, OnDestroy {
private user: User = null;
private destroy$ = new Subject();
constructor(private http: HttpClient) {}
ngOnInit() {
this.http
.get<User>('api/user/id')
.pipe(takeUntil(this.destroy$))
.subscribe(user => {
this.user = user;
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}