November 25, 2021

Angular - Using Takeuntil RxJS Operator in Base Class

In the last post , we have seen how to use takeuntil operator to automatically unsubscribe from an observable. takeuntil operator makes it easier to manage the control to unsubscribe from multiple observables.

In that exmaple we have implemented the takeuntil operator in a single component. If you need to implement the same technique in multiple components then you have to repeat the same logic in every component.

In this post we will see how we can implement takeUntil operator in a base class, so that we dont have to repeat the similar code in multiple components.

Here is the code for base class:

import { Subject } from 'rxjs';
import { Component, OnDestroy } from '@angular/core';


@Component({
    template: ''
})
export abstract class BaseComponent implements OnDestroy {

protected componentDestroyed$ = new Subject();

    constructor() { }

    ngOnDestroy() {
        this.componentDestroyed$.next();
        this.componentDestroyed$.complete();
    }
}

And the ChildComponent inheriting the BaseComponent class defined above.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { takeUntil } from 'rxjs/operators';
import { Service1 } from 'Service1';
import { Service2 } from 'Service2';
import { BaseComponent } from 'src/app/models/base-component.model';

@Component({ ... })
export class ChildComponent extends BaseComponent implements OnInit  {

  constructor(private myservice1: Service1, private myservice2: Service2) {}

  ngOnInit() {
    
    this.myservice1.getData()
    .pipe(takeUntil(this.componentDestroyed$)) //componentDestroyed$ is defined in BaseComponent
    .subscribe(({data}) => {
      console.log(data);
    });
	
    this.myservice2.getData()
    .pipe(takeUntil(this.componentDestroyed$))
    .subscribe(({data}) => {
      console.log(data);
    });	
  }
 
 }

Note that, we don't need to implment OnDestroy (ngOnDestroy handler) in ChildComponent to call the next() and complete() methods for subject componentDestroyed$, because we have already defined this in the BaseComponent.

References:

Related Post(s):

No comments:

Post a Comment