// Service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class DataService {
private dataSubject = new Subject<string>();
data$ = this.dataSubject.asObservable();
sendData(data: string) {
this.dataSubject.next(data);
}
}
// Component A
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component-a',
template: `<button (click)="sendData()">Send Data</button>`
})
export class ComponentA {
constructor(private dataService: DataService) {}
sendData() {
this.dataService.sendData('Hello from Component A');
}
}
// Component B
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component-b',
template: `<p>{{data}}</p>`
})
export class ComponentB implements OnInit {
data!: string;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.data$.subscribe(data => {
this.data = data;
});
}
}
These methods provide a robust way to handle communication between Angular components, ensuring data is passed efficiently and events are handled appropriately