In angular to share data among component we use Shared Service with Subject or BrhaviorSubject observable like below,
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class DataService {
private subject = new Subject<any>();
// Method to set navmenu //
public sendData(data: boolean) {
this.subject.next(data);
}
// Method to clear navmenu //
public clearData() {
this.subject.next();
}
// Method to get navmenu //
public getData(): Observable<any> {
return this.subject.asObservable();
}
}
But we can achieve the same without using Subject or BehaviorSubject observable. In the below example as the Component A and B both shares the instance of the EmailService, so if the component A change the value (emailService.apiKey) then the same reflect in the component B and vice-versa, like below,
class EmailService{
public apiKey: string = 'ABCD1234';
}
@Component({
selector: 'component-a',
template: `
Component A - {{emailService.apiKey}}
<button (click)="changeApiKey()">Change Key</button>
`
})
export class A{
public emailService: EmailService;
constructor(emailService: EmailService){
this.emailService = emailService;
}
changeApiKey(){
this.emailService.apiKey = "XYZ1234";
}
}
@Component({
selector: 'component-b',
template: `
Component B - {{emailService.apiKey}}
<button (click)="changeApiKey()">Change Key</button>
`
})
export class B{
public emailService: EmailService;
constructor(emailService: EmailService){
this.emailService = emailService;
}
changeApiKey(){
this.emailService.apiKey = "ABCD1234";
}
}
@Component({
selector: 'app-root',
template: `
<component-a></component-a>
<br />
<component-b></component-b>
`,
providers: [
EmailService
]
})
export class AppComponent {
}
Can someone please explain why most of the examples and tutorials use observable in shared service. What's the advantage in using that ??