Communicating Between Sibling Components in Angular via a Service
1. Create a Shared Service
Create a shared service in a common directory using the CLI command: ng g s path/service-name, e.g., ng g s service/storage. This generates storage.service.ts with the following implementation:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StorageService {
// Create a BehaviorSubject with an initial value of 0
subject: BehaviorSubject<any> = new BehaviorSubject<any>(0);
}
2. Import and Register the Service in AppModule
In app.module.ts, import and regitser StorageService as a providre:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ComponentOneComponent } from './component-one/component-one.component';
import { ComponentTwoComponent } from './component-two/component-two.component';
import { StorageService } from './service/storage.service';
@NgModule({
declarations: [
AppComponent,
ComponentOneComponent,
ComponentTwoComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Component A (Sending Data)
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { StorageService } from '../service/storage.service';
@Component({
selector: 'app-component-one',
templateUrl: './component-one.component.html',
styleUrls: ['./component-one.component.less']
})
export class ComponentOneComponent implements OnInit {
inputValue = '';
constructor(
public storageService: StorageService,
private router: Router
) { }
ngOnInit(): void { }
send(): void {
this.router.navigate(['/two']);
// Publish the input value via the shared service
this.storageService.subject.next(this.inputValue);
}
}
4. Component B (Receivnig Data)
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { StorageService } from '../service/storage.service';
@Component({
selector: 'app-component-two',
templateUrl: './component-two.component.html',
styleUrls: ['./component-two.component.less']
})
export class ComponentTwoComponent implements OnInit, OnDestroy {
data: any;
isVisible = false;
private subscription: Subscription;
constructor(public storageService: StorageService) {
// Subscribe to the subject and capture the subscription
this.subscription = this.storageService.subject.subscribe(value => {
this.data = value;
console.log('Data received');
});
}
showData(): void {
this.isVisible = true;
}
ngOnInit(): void { }
ngOnDestroy(): void {
// Unsubscribe to avoid memory leaks
this.subscription.unsubscribe();
}
}