Angular Observable Subject Example Sharing Data

Angular is a powerful framework that provides developers with a plethora of tools and features to build robust and scalable applications. One of the key features is the Observable Subject, which allows you to share data between components and services in a reactive and asynchronous manner.

In this article, we will explore how to use Angular Observable Subject to share data between components and services in an efficient and effective manner. We will also look at some frequently asked questions about using Angular Observable Subject.

What is Angular Observable Subject?

In Angular, an Observable is a powerful tool for handling asynchronous event streams. It allows you to subscribe to an event stream and be notified when new events occur. A Subject, on the other hand, is both an Observable and an Observer. It can be used to emit events to multiple subscribers, making it an efficient and elegant way to share data among components and services.

Creating an Angular Observable Subject

Before we begin, let us create an Angular application using the Angular CLI. Navigate to a directory of your choice and run the following command:

“`html
ng new my-angular-app
“`

This will create a new Angular application with the basic setup and configuration. We can now create a new Angular service that will use the Observable Subject to share data between components:

“`html
ng generate service DataService
“`

This will create a new service called DataService that we can use to store and manipulate data. Inside the DataService class, we will declare an Observable Subject variable called subject:

“`html
import { Injectable } from ‘@angular/core’;
import { Subject } from ‘rxjs’;

@Injectable({
providedIn: ‘root’
})
export class DataService {
private subject = new Subject();

sendUpdate(message: any) {
this.subject.next({ text: message });
}

getUpdate() {
return this.subject.asObservable();
}
}
“`

The subject variable is private and can only be accessed within the service. We declare two methods that allow us to send and receive data from the subject. The sendUpdate method is used to send data to the subject, while the getUpdate method allows components to subscribe to the subject and receive data.

Using Angular Observable Subject in a Component

Now that we have created the DataService, we can use it in a component to share data. Let us create a new component called SenderComponent:

“`html
ng generate component Sender
“`

Inside the SenderComponent class, we will import the DataService and create a new instance of it in the constructor:

“`html
import { Component } from ‘@angular/core’;
import { DataService } from ‘../data.service’;

@Component({
selector: ‘app-sender’,
templateUrl: ‘./sender.component.html’,
styleUrls: [‘./sender.component.css’]
})
export class SenderComponent {

message = ”;

constructor(private data: DataService) { }

sendMessage() {
this.data.sendUpdate(this.message);
this.message = ”;
}
}
“`

In this example, we create a variable called message that will hold the data that we want to send to the DataService. We also import the DataService and create an instance of it in the constructor. The sendMessage method is called when the user submits the form, and it sends the message to the DataService using the sendUpdate method. It also clears the message variable so that the form can be reset.

Now let us create a new component that will receive the data:

“`html
ng generate component Receiver
“`

In the ReceiverComponent class, we will import the DataService and subscribe to the data using the getUpdate method:

“`html
import { Component, OnInit } from ‘@angular/core’;
import { DataService } from ‘../data.service’;

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

message = ”;

constructor(private data: DataService) { }

ngOnInit() {
this.data.getUpdate().subscribe(message => {
this.message = message.text;
});
}

}
“`

In this component, we import the DataService and create an instance of it in the constructor. We also use the ngOnInit method to subscribe to the subject and receive data using the getUpdate method. The message variable is updated whenever new data is received from the subject.

Conclusion

Using Angular Observable Subject is an efficient and effective way to share data between components and services in an Angular application. By creating a Subject in a service, you can emit events to multiple subscribers, making it easy to share data reactively and asynchronously.

FAQs

What is the difference between an Observable and a Subject?

In Angular, an Observable is a representation of an asynchronous data stream. It allows you to subscribe to an event stream and be notified when new events occur. A Subject is a type of Observable that can act as both an Observable and an Observer. It can emit events to multiple subscribers, making it an efficient way to share data among components and services.

Why use Angular Observable Subject?

Angular Observable Subject provides a reactive and asynchronous way to share data between components and services. By creating a Subject in a service, you can emit events to multiple subscribers, making it easy to share data reactively and asynchronously. This can improve the performance and scalability of your Angular application by reducing the need for manual data synchronization.

How can I unsubscribe from an Angular Observable Subject?

Angular Observable Subject provides an unsubscribe method that can be called to stop receiving data from the subject. To unsubscribe, you can store the subscription in a variable and call the unsubscribe method when you no longer need the data:

“`html
subscription = this.data.getUpdate().subscribe(message => {
this.message = message.text;
});

ngOnDestroy() {
this.subscription.unsubscribe();
}
“`

In this example, the subscription variable is used to store the subscription returned by the getUpdate method. The ngOnDestroy method is called when the component is destroyed, and it calls the unsubscribe method to stop receiving data from the subject.

Similar Posts