Recently, I dived into learning Angular and came across an interesting example in the official documentation discussing parent-child communication using a service:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class MissionService {
// Observable string sources
private missionAnnouncedSource = new Subject<string>();
private missionConfirmedSource = new Subject<string>();
// Observable string streams
missionAnnounced$ = this.missionAnnouncedSource.asObservable();
missionConfirmed$ = this.missionConfirmedSource.asObservable();
// Service message commands
announceMission(mission: string) {
this.missionAnnouncedSource.next(mission);
}
confirmMission(astronaut: string) {
this.missionConfirmedSource.next(astronaut);
}
}
One particular section of the code puzzled me:
// Observable string streams
missionAnnounced$ = this.missionAnnouncedSource.asObservable();
missionConfirmed$ = this.missionConfirmedSource.asObservable();
I understand that .asObservable()
creates a new Observable with the Subject as the source. But why do we need it? Isn't missionAnnouncedSource
already an observable on its own?
Why not simplify the service like this:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class MissionService {
// Observable string sources
missionAnnouncedSource = new Subject<string>();
missionConfirmedSource = new Subject<string>();
// Service message commands
announceMission(mission: string) {
this.missionAnnouncedSource.next(mission);
}
confirmMission(astronaut: string) {
this.missionConfirmedSource.next(astronaut);
}
}
While adjustments would be needed in components, I fail to see any drawbacks:
//astronaut.component.ts
constructor(private missionService: MissionService) {
this.subscription = missionService.missionAnnouncedSource.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
});
}
Is this following a certain convention or am I overlooking something?