The Observer Pattern is a behavioral design pattern widely used in software development to establish a one-to-many dependency between objects. In the context of Angular and AngularJS, this pattern plays a crucial role in facilitating communication between components, allowing them to react to changes in state or data.
Overview of the Observer Pattern: In the Observer Pattern, there are two main roles: the Subject and the Observer. The Subject is the object that holds the state or data of interest, and the Observer is the object that wants to be notified of any changes in the Subject.
Key Components:
- Subject: The entity that maintains a list of observers, provides methods to attach and detach observers, and notifies them of state changes.
- Observer: The object that is interested in the state changes of the Subject. It registers itself with the Subject, and when a change occurs, it is notified through a specific method.
Example in Angular/AngularJS:
Let’s consider a simple scenario where we have a counter component, and we want another component to be notified whenever the counter value changes.
Subject - CounterService:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class CounterService {
private counterSubject = new Subject();
getCounterObservable() {
return this.counterSubject.asObservable();
}
updateCounter(value: number) {
this.counterSubject.next(value);
}
}
Observer – DisplayComponent:
import { Component, OnInit } from '@angular/core';
import { CounterService } from '../services/counter.service';
@Component({
selector: 'app-display',
template: '
Current Counter Value: {{ counterValue }}
',
})
export class DisplayComponent implements OnInit {
counterValue: number = 0;
constructor(private counterService: CounterService) {}
ngOnInit() {
this.counterService.getCounterObservable().subscribe((value) => {
this.counterValue = value;
});
}
}
Usage in Another Component:
import { Component } from '@angular/core';
import { CounterService } from '../services/counter.service';
@Component({
selector: 'app-counter',
template: `
`,
})
export class CounterComponent {
constructor(private counterService: CounterService) {}
incrementCounter() {
// Logic to increment the counter
this.counterService.updateCounter(/* updated counter value */);
}
decrementCounter() {
// Logic to decrement the counter
this.counterService.updateCounter(/* updated counter value */);
}
}
Conclusion: In this post, we explored the Observer Pattern in the context of Angular/AngularJS using a simple example. The CounterService acts as the Subject, holding the counter value, while the DisplayComponent acts as the Observer, reacting to changes in the counter value. This pattern promotes loose coupling and enhances the maintainability and scalability of Angular applications.