Angular Tutorial: Subject, BehaviorSubject

beginner
13 min

Angular Tutorial: Subject, BehaviorSubject

Welcome to this comprehensive guide on Angular's Subject and BehaviorSubject! Let's dive into the world of reactive programming, where we'll learn how to manage data flow efficiently in our Angular applications.

Understanding Subject

Subject is an observable that can multicast its observations by default. It can send and broadcast messages (events) to multiple Observers (subscribers) and can be used to communicate between components.

šŸ’” Pro Tip: Subjects can be used to create services that act as a central hub for sharing data between components.

typescript
import { Subject } from 'rxjs'; // Create a new Subject const mySubject = new Subject(); // Subscribe to the Subject mySubject.subscribe({ next: value => console.log('Next: ', value), complete: () => console.log('Completed') }); // Send a value to the Subject mySubject.next('Hello, Subject!');

Understanding BehaviorSubject

BehaviorSubject is a special type of Subject that stores the last emitted value. This means it has an initial value that gets passed to all new subscribers.

šŸŽÆ Key Difference: BehaviorSubject always has an initial value, whereas Subject starts emitting only when a subscriber subscribes to it.

typescript
import { BehaviorSubject } from 'rxjs'; // Create a new BehaviorSubject with initial value const myBehaviorSubject = new BehaviorSubject('Hello, BehaviorSubject!'); // Subscribe to the BehaviorSubject myBehaviorSubject.subscribe({ next: value => console.log('Next: ', value), complete: () => console.log('Completed') }); // Send a new value to the BehaviorSubject myBehaviorSubject.next('New Value');

Using Subjects in Angular

Now that we've covered the basics, let's explore how to use Subjects in an Angular application. We'll create a simple service and a component to demonstrate this.

Creating a Subject Service

typescript
// subject.service.ts import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SubjectService { private mySubject = new Subject(); constructor() {} getSubject() { return this.mySubject; } sendValue(value: string) { this.mySubject.next(value); } }

Using the Subject Service in a Component

typescript
// app.component.ts import { Component } from '@angular/core'; import { SubjectService } from './subject.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { private mySubject = this.subjectService.getSubject(); constructor(private subjectService: SubjectService) {} ngOnInit() { this.mySubject.subscribe({ next: value => console.log('Next: ', value) }); } sendValue() { this.subjectService.sendValue('Hello, from the Component!'); } }

Quiz

Quick Quiz
Question 1 of 1

What is the main difference between Subject and BehaviorSubject?

By the end of this tutorial, you should have a solid understanding of Angular's Subject and BehaviorSubject, and how to use them effectively in your applications. Happy coding! šŸš€