RxJS Subject In Angular

Hi Friends, This is Lakshman here.

As part of the Series "Angular Best Practices".

Today, We will RxJS Subject in Angular.

Pre-requisites:

The pre-requisites are

RxJS Subject

A Subject is like an Observable, Where we can subscribe to information and receives it when new data is available.

Now, we are going to see how we could use Subject in Angular.

Sent Info between Components.

At First, we need a service to define our Subject as below,

import { Observable, Subject } from 'rxjs';

private infoSubject = new Subject<any>();

Then we need to set up the method to get Observable, Send and Clear Info as below,

import { Observable, Subject } from 'rxjs';
...

onInfo(): Observable<any> {
    return this.infoSubject.asObservable();
}

sendInfo(info: any) {
    if (info !== undefined) {
        this.infoSubject.next(info);
    }
}

clearInfo() {
    this.infoSubject.next();
}

Once this is done, we can start configure our Component to sent and receive info as below,

import { Component, OnDestroy, OnInit } from "@angular/core";
import { Subscription } from "rxjs";
import { Info } from "./IInfo.interface";
import { SubjectService } from "./subject.service";

@Component({
  selector: "app-subject",
  templateUrl: "./subject.component.html",
  styleUrls: ["./subject.component.scss"],
})
export class SubjectComponent implements OnInit, OnDestroy {
  info: Info;
  subscription: Subscription;

  constructor(private subjectService: SubjectService) {}

  ngOnInit(): void {
    this.subscription = this.subjectService
      .onInfo()
      .subscribe((info) => (this.info = info));
  }

  ngOnDestroy(): void {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }

  SentMessage() {
    this.subjectService.sendInfo(new Info("Message From Main", "Main"));
  }
}

NOTE: Always user Subscription Option while subscribing to Observable inside component, where we can unsubscribe on OnDestroy Event.

On the Call of SentMessage, it calls our Service and Pushes information. If other Components have subscribed to the same service, they will receive it.

To Display this information on HTML see below,

<h3>Subject Main Component</h3>
<div class="row">
  <div class="col-12">
    Current Value on Subject is <b>{{ info?.message }}</b>
  </div>
</div>
<div class="row mt-2">
  <div class="col-12">
    <button class="btn btn-default" (click)="SentMessage()">
      Sent Message
    </button>
  </div>
</div>

NOTE: When you display information from Object, always use ? after object name.

You can use this technique to share information with other modules, components, etc.,

Info

Like Subject, there is one more option called BehaviorSubject if you want to initialize some default values.

That wraps up the RxJS in Angular

You may also access to source code on GitHub by Click Here

On-road head, we will discuss a lot of things.

Looking forward to your comments and share your feedback.

Until that, I am Lakshman, Signing Off.

Comments

Popular posts from this blog

Model Mapper in Angular

Implement Logging in Angular with Firebase

Dockerize Angular App for Dev