How to Unsubscribe from a Subscription in Angular 4

Here is a solution presented from a student named Henry Goh on how to unsubscribe from an Angular 4 subscription:

Import the OnDestroy and Subject classes

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Observable, Subject } from "rxjs/Rx";

 

Implement the OnDestroy class

export class DocumentsComponent implements OnInit, OnDestroy 

 

Add a new field in your DocumentsComponent class

ngUnsubscribe: Subject<void> = new Subject<void>(); 

 

In ngOnInit(), call the takeUntil method and insert the new field as argument.

ngOnInit() {
  const timer = Observable.timer(0, 5000);
  timer.takeUntil(this.ngUnsubscribe)
    .subscribe(() => { this.getDocuments(); });
}

 

5. Implement the ngOnDestroy() method

ngOnDestroy() {
  this.ngUnsubscribe.next();
  this.ngUnsubscribe.complete();
}