Angular Async Pipe – Unsubscribe (Best Practices 2)

Use async pipe or unsubscribe properly.

For example if you ignite a http get request by visiting X component and then route to Y component without waiting your get request to complete, your get request in X component still runs.

There are several ways to handle that issue. First one is, using async pipe. Async pipe automatically unsubscribes when you change your route.

//example.component.ts

export class ExampleComponent implements OnInit {

    constructor(private http: HttpClient) { }
  
    recipes: Observable<any[]>;
  
    ngOnInit(): void {
      this.recipes = this.http.get<any[]>("URL").pipe();
    }
  
  }
// example.component.html

<ul>
<li *ngFor="let recipe of recipes | async">{{ recipe.title }}</li>
</ul>

Second way is to use unsubscribe in ngOnDestroy method.

export class ExampleComponent implements OnInit, OnDestroy {

    constructor(private http: HttpClient) { }
  
    subscription;
  
    ngOnDestroy(): void {
     this.subscription.unsubscribe();
    }
  
    ngOnInit(): void {
      this.subscription = this.http.get<any[]>("URL").subscribe();
    }
  
  }

Third way is to use subjects of RxJS.

export class ExampleComponent implements OnInit, OnDestroy {

  constructor(private http: HttpClient) { }

  unsubscribeSubject = new Subject();

  ngOnDestroy(): void {
   this.unsubscribeSubject.next();
   this.unsubscribeSubject.complete();
  }

  ngOnInit(): void {
    this.http.get<any[]>("URL")
    .pipe(takeUntil(this.unsubscribeSubject)).subscribe();
  }

}