1//Please note that there are many ways to unsubscribe, this is one of them
2import { Subscription } from 'rxjs';
3
4private searchEventSubscription: Subscription;
5
6export class someComponent OnInit, OnDestroy {
7
8 constructor(private someService: SomeService) { }
9
10 ngOnInit() {
11 this.searchEventSubscription = this.someService.someMethod.subscribe(result => {
12 doSomething(result);
13 });
14 }
15
16 ngOnDestroy() {
17 this.searchEventSubscription.unsubscribe()
18 }
1/* Best practice is to create a base class and move generik handling to it */
2
3import { Subscription, Observable } from 'rxjs';
4import { OnDestroy } from '@angular/core';
5
6
7export abstract class ComponentBase implements OnDestroy {
8
9 set subs(subscription: Subscription) {
10 this.subscriptioions.add(subscription);
11 }
12
13 private subscriptioions = new Subscription();
14
15 constructor() {};
16
17 subscribe(service: Observable<any>, successFn: (value: any) => void, errorHandler?: (value: any) => void) {
18 this.subs = service.subscribe(successFn, errorHandler || this.errorHandler);
19 }
20
21 ngOnDestroy() {
22 this.subscriptioions.unsubscribe();
23 }
24
25 private errorHandler(error) {
26 // TODO: generic error handling
27 }
28}
29
30/* implementation in a component */
31// No need to explicitly subscribe or unsubscribe on destroy
32
33const product$ = this.productService.getProducts(productId);
34this.subscribe(product$, (product) => {
35 // TODO: use product
36})
37
38
1import { Component, OnInit, OnDestroy } from '@angular/core';
2import { HttpClient } from '@angular/common/http';
3
4import { Subject } from 'rxjs';
5import { takeUntil } from 'rxjs/operators';
6
7interface User {
8 id: string;
9 name: string;
10 age: number;
11}
12
13@Component({
14 selector: 'app-foobar',
15 templateUrl: './foobar.component.html',
16 styleUrls: ['./foobar.component.scss'],
17})
18export class FoobarComponent implements OnInit, OnDestroy {
19 private user: User = null;
20 private destroy$ = new Subject();
21
22 constructor(private http: HttpClient) {}
23
24 ngOnInit() {
25 this.http
26 .get<User>('api/user/id')
27 .pipe(takeUntil(this.destroy$))
28 .subscribe(user => {
29 this.user = user;
30 });
31 }
32
33 ngOnDestroy(): void {
34 this.destroy$.next(); // trigger the unsubscribe
35 this.destroy$.complete(); // finalize & clean up the subject stream
36 }
37}