0% found this document useful (0 votes)
13 views12 pages

Using Subject

The document explains how to use BehaviorSubject from RxJS for real-time data sharing between unrelated Angular components through a service. It provides a complete code example demonstrating the creation of a service and two components: one for sending messages and another for receiving them. The BehaviorSubject allows components to share the latest value and automatically update when changes occur, making it ideal for real-time applications.

Uploaded by

muthyalasowmya10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views12 pages

Using Subject

The document explains how to use BehaviorSubject from RxJS for real-time data sharing between unrelated Angular components through a service. It provides a complete code example demonstrating the creation of a service and two components: one for sending messages and another for receiving them. The BehaviorSubject allows components to share the latest value and automatically update when changes occur, making it ideal for real-time applications.

Uploaded by

muthyalasowmya10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Using Subject (Real-time Data Sharing)

Using BehaviorSubject in service.


import { BehaviorSubject } from 'rxjs';

message = new BehaviorSubject<string>('Hello');


currentMessage = [Link]();
✔ Best for real-time updates
✔ Used in large applications

This is also called as “Angular service communication”


Complete code for using “BehaviorSubject” for real-time data sharing between unrelated
components.
We use BehaviorSubject from RxJS.

Note: In Angular, Observables are used to handle asynchronous data streams such as HTTP
requests, user input events, and real-time data updates. They come from the RxJS library.

Note:In Angular, BehaviorSubject is a special type of Observable from RxJS used for sharing
data between components and storing the latest value.

Complete code for “Using Subject (Real-time Data Sharing)”


Scenario:
Two unrelated components share data using a service.

1) Create Service
ng g s DataService

src/app/[Link] (363 bytes)


src/app/[Link] (124 bytes)

File: [Link]
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {

// Step 1: Create BehaviorSubject with default value


private messageSource = new BehaviorSubject<string>('Hello');

// Step 2: Convert to Observable


currentMessage$ = [Link]();

constructor() {}

// Step 3: Method to change message


changeMessage(message: string) {
[Link](message);
}
}

2) Component 1 (Sender)
Command is: ng g c component1
The following files are generated:
src/app/component1/[Link] (582 bytes)
src/app/component1/[Link] (213 bytes)
src/app/component1/[Link] (0 bytes)
src/app/component1/[Link] (26 bytes)
File: [Link]
import { Component } from '@angular/core';
import { DataService } from '../data-service';

@Component({
selector: 'app-component1',
templateUrl: './[Link]',
})
export class Component1 {

constructor(private dataService: DataService) {}

sendMessage(value: string) {
[Link](value);
}
}

File:[Link]
<h2>Component 1</h2>

<input #msg type="text" placeholder="Enter message">


<button (click)="sendMessage([Link])">Send</button>

3) Component 2 (Receiver)
Command is: ng g c component2
The following files are generated:
src/app/component2/[Link] (582 bytes)
src/app/component2/[Link] (213 bytes)
src/app/component2/[Link] (0 bytes)
src/app/component2/[Link] (26 bytes)

File: [Link]
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data-service';

@Component({
selector: 'app-component2',
templateUrl: './[Link]',
})
export class Component2 implements OnInit {
message: string = '';
constructor(private dataService: DataService) {}

ngOnInit() {
[Link]$.subscribe(msg => {
[Link] = msg;
});
}
}

File: [Link]
<h2>Component 2</h2>
<p>Message: {{ message }}</p>

4) Use Components in [Link]


<app-component1></app-component1>
<hr>
<app-component2></app-component2>

Output:

Enter some text in text box of “Component1” and click on “send” button.
How It Works
1. BehaviorSubject stores the latest value.
2. Component1 sends data using next().
3. Component2 subscribes to the observable.
4. Whenever the value changes → Component2 updates automatically.
5. New subscribers immediately receive the last value.

🎯 Why BehaviorSubject (Instead of Subject)?

Subject BehaviorSubject

No initial value Requires initial value

No last value replay Sends last value immediately

Used for events Used for state


Line-by-Line explanation for the above program:

1) [Link] (Service File)


import { Injectable } from '@angular/core';
 Imports Injectable decorator from Angular core.
 This allows the service to be injected into components.

import { BehaviorSubject } from 'rxjs';


 Imports BehaviorSubject from RxJS library.
 BehaviorSubject is used to share and update data in real-time.

@Injectable({
providedIn: 'root',
})
 @Injectable makes this class a service.
 providedIn: 'root' means:
 Only one instance of this service will be created.
 It is available throughout the whole application.

export class DataService {


 Defines the service class named DataService.
 export allows other files to use it.

private messageSource = new BehaviorSubject<string>('Hello');


 Creates a BehaviorSubject named messageSource.
 <string> means it stores string values.
 'Hello' is the default value.
 private means it can only be accessed inside this class.
🔹 Important:
BehaviorSubject:
 Stores current value
 Sends last value to new subscribers
currentMessage$ = [Link]();
 Converts BehaviorSubject into an Observable.
 $ at the end means it is an Observable (naming convention).
 Other components can subscribe to this.
🔹 Why convert?
Because we don’t want other components to directly modify the subject.

constructor() {}
 Empty constructor.
 Runs when service is created.

changeMessage(message: string) {
 Method to update the message.
 Accepts a string parameter.

[Link](message);
 .next() sends new value to all subscribers.
 Whenever this runs → all subscribed components receive updated value.

2) Component 1 (Sender)
import { Component } from '@angular/core';
 Imports Angular Component decorator.

import { DataService } from '../data-service';


 Imports the service to use it in this component.

@Component({
selector: 'app-component1',
templateUrl: './[Link]',
})
 Defines component metadata.
 selector → HTML tag name
 templateUrl → HTML file linked

export class Component1 {


 Defines component class.

constructor(private dataService: DataService) {}


 Dependency Injection.
 Angular injects DataService into this component.
 private makes it accessible inside this class.

sendMessage(value: string) {
 Method to send message to service.

[Link](value);
 Calls service method.
 Updates BehaviorSubject with new value.

[Link]
<h2>Component 1</h2>
 Heading text.

<input #msg type="text" placeholder="Enter message">


 Textbox for user input.
 #msg is a template reference variable.
 Used to access input value.

<button (click)="sendMessage([Link])">Send</button>
 When button is clicked:
 Calls sendMessage()
 Passes textbox value to it.
3) Component 2 (Receiver)
import { Component, OnInit } from '@angular/core';
 Imports Component and lifecycle hook OnInit.

import { DataService } from '../data-service';


 Imports the shared service.

export class Component2 implements OnInit {


 Component class.
 implements OnInit means it uses ngOnInit lifecycle hook.

message: string = '';


 Local variable to store message.
 Initially empty.

constructor(private dataService: DataService) {}


 Injects DataService into this component.

ngOnInit() {
 Lifecycle method.
 Runs automatically after component loads.

[Link]$.subscribe(msg => {
 Subscribes to Observable.
 Whenever message changes → this runs.

[Link] = msg;
 Updates local variable with new message.
 UI automatically updates because Angular detects changes.

[Link]
<h2>Component 2</h2>
 Heading.

<p>Message: {{ message }}</p>


 Displays message using interpolation.
 Whenever message changes → UI updates automatically.

4) [Link]
<app-component1></app-component1>
<hr>
<app-component2></app-component2>
 Displays both components.
 <hr> adds horizontal line.

Complete Flow (Very Important for Interviews)


1) App loads
2) Service is created (singleton)
3) BehaviorSubject contains default value: "Hello"
4) Component2 subscribes → receives "Hello"
5) User types message in Component1
6) Clicks Send
7) changeMessage() runs
8) BehaviorSubject .next() sends new value
9) Component2 receives updated value
10) UI updates automatically

 Why BehaviorSubject is Used?


Because:
 It stores latest value
 New subscribers get current value immediately
 Perfect for real-time data sharing

Interview Question: What is Component communication in Angular?


Ans: Component communication in Angular is the process of sharing data between
components using @Input(), @Output(), Services, and RxJS Subjects

You might also like