//Please note that there are many ways to unsubscribe, this is one of them
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()
}
import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { BookService } from '../books.service';
@Component({
selector: 'app-books',
templateUrl: './books.component.html'
})
export class BooksComponent implements OnDestroy, OnInit {
private ngUnsubscribe = new Subject();
constructor(private booksService: BookService) { }
ngOnInit() {
this.booksService.getBooks()
.pipe(
startWith([]),
filter(books => books.length > 0),
takeUntil(this.ngUnsubscribe)
)
.subscribe(books => console.log(books));
this.booksService.getArchivedBooks()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(archivedBooks => console.log(archivedBooks));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
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(); // trigger the unsubscribe
this.destroy$.complete(); // finalize & clean up the subject stream
}
}