DEV Community

Jameer Khan
Jameer Khan

Posted on • Originally published at stackblogger.com

Angular and RxJS: Refresh a Component From Another

RxJS is Reactive Extensions of JavaScript. It provides various handy Observables and Operators to work within Angular. It becomes important in scalable application development. This tutorial will guide you to reload or refresh a component from another using RxJS Observables. I will use a common service that will be responsible to keep the event emitters.

Real examples

Building a large-scale application requires an optimized and well-structured code, only then it will give the best performance measurement. There are many situations where we need to refresh a part of a component from another component’s action. Here are a few of them.

Refresh data table at component after action on another

This is the most common scenario when building an application. You have a data table on the list component and there is another component for Add/Edit/Delete. You want to refresh the data table when a record is added/edited/deleted.

Reload a dropdown after action on a different component

A dropdown data can be refreshed using RxJS Subject or EventEmitter from a different component. It requires a common service to be used by both of the components. Emit the event from the source component and subscribe to the listener. Reload the data in the subscription.

Refresh multi-lingual content explicitly

This situation happens when Angular’s Change Detection is not able to detect the language change button click. In that case, you want to manually emit an event at the language change action and refresh the multi-language content.

You can use any one of the below events generation mechanisms to implement any of the above examples. You can also use it in any other use case as per your requirement. Let’s start code implementation.

Refresh a Component From Another Using RxJS

RxJS observables and operators will be used to reload a part of data at a component from a different component. We will look into the ways one by one with examples.

Reload part of component using RxJS Subject

RxJS Subject is an Observable that is used to multicast the event to multiple observers. We will use Subject to notify the component on some action and reload the part.

data.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  subjectNotifier: Subject<null> = new Subject<null>();

  constructor() { }

  notifyAboutChange() {
    this.subjectNotifier.next();
  }
}
Enter fullscreen mode Exit fullscreen mode

A variable subjectNotifier with Subject Data Type is declared. null type is passed in the Subject argument because I don’t need to send any value with notification. If you want to send a value along with the notification, you can specify there the value type and send the value in this.subjectNotifier.next();

Call the notifyAboutChange method from the origin component.

sender.component.ts

This is the event originator component. An event will be emitted on add/edit/delete record or as per your requirement. The event will be then subscribed by the receiver component.

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-sender',
  templateUrl: './sender.component.html',
  styleUrls: ['./sender.component.scss']
})
export class SenderComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.notifyForChange(); // call this method after add/edit/delete or as per your requirement
  }

  notifyForChange() {
    this.dataService.notifyAboutChange();
  }
}
Enter fullscreen mode Exit fullscreen mode

receiver.component.ts

Subscribe to the event in receiver component.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from '../data.service';

@Component({
  selector: 'app-receiver',
  templateUrl: './receiver.component.html',
  styleUrls: ['./receiver.component.scss']
})
export class ReceiverComponent implements OnInit, OnDestroy {

  notifierSubscription: Subscription = this.dataService.subjectNotifier.subscribe(notified => {
    // originator has notified me. refresh my data here.
  });

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
  }

  ngOnDestroy() {
    this.notifierSubscription.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: I have used a Subscription variable notifierSubscription. I can unsubscribe it in ngOnDestroy to prevent memory leaks when component is destroyed.

Refresh part of component using EventEmitter

data.service.ts

Declare an EventEmitter variable.

eventEmitterNotifier: EventEmitter<null> = new EventEmitter();
Enter fullscreen mode Exit fullscreen mode

Again, I am using null value in the EventEmitter argument because I don’t need to pass any value. I only need to notify my listener. If you need to pass data along with event notification, you can provide the data reference and pass the value while emitting the event.

Emit the event.

notifyAboutChange() {
  this.eventEmitterNotifier.emit();
}
Enter fullscreen mode Exit fullscreen mode

Call the emit() method in notifyAboutChange in data.service.ts file. Consume notifyAboutChange method from sender component to emit event.

sender.component.ts

Call the notifyAboutChange service method to emit the event on add/edit/delete action or any other action as per your need.

constructor(private dataService: DataService) { }

ngOnInit(): void {
  this.notifyForChange(); // call this method after add/edit/delete or as per your requirement
}

notifyForChange() {
  this.dataService.notifyAboutChange();
}
Enter fullscreen mode Exit fullscreen mode

This will invoke the event and the listener will be notified immediately.

receiver.component.ts

Subscribe to the event in the same way we did for the RxJS Subject.

notifierSubscription: Subscription = this.dataService.eventEmitterNotifier.subscribe(notified => {
  // originator has notified me. refresh my data here.
});

constructor(private dataService: DataService) { }

ngOnInit(): void {
}

ngOnDestroy() {
  this.notifierSubscription.unsubscribe();
}
Enter fullscreen mode Exit fullscreen mode

Note: Unsubscribe the subscription in ngOnDestroy to prevent unnecessary memory leakage.

Conclusion

Events generation is one of the most used mechanisms in Angular development. RxJS comes to mind when implementing such use cases. This article explains how to refresh a part of component from another component with the help of RxJS Observables.

Read How to Pass Data Between Components Using RxJS.

Also Read:

5 Best Google Charts to Use in Angular
Angular Material 12 Table, Sorting, Searching & Pagination
RxJS forkJoin: Definition and Real World Uses
5 Great SEO Ideas To Improve Angular Website Ranking
Real World Examples of 5 Common Observable Operators

Top comments (0)