Reputation: 2805
I have this code inside a component, what am I seeing in the console is this message: 'from component 1: mission started'. So it's getting the response correctly from the service, but once it completes I want to print the message 'successed!!' and that's never happening... How can I do something when the subscribe()
completes?
onClick() {
this.service.announceMission('mission started');
this.service.missionAnnounced$.subscribe(response => console.log('from component 1: ' + response),
error => console.log('error: ', error),
() => console.log('successed!!'));
}
And this is the code I have in my service:
export class MissionService {
// Observable string sources
private missionAnnouncedSource = new BehaviorSubject("not started yet");
private missionConfirmedSource = new BehaviorSubject("not started yet");
// 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);
}
}
Upvotes: 1
Views: 132
Reputation: 5026
An observable does not complete until you say so.
const mySource = new Subject<string>();
mySource.subscribe(
(value: string) => {console.log('value: ', value)},
(error: any) => {console.error(error)},
() => {console.log('completed')},
);
mySource.next('a');
mySource.next('b');
mySource.next('c');
subject.complete();
mySource.next('d');
With output :
value: a
value: b
value: c
completed
The d
won't be written after completion.
So for your case, you should add a completeMission()
function that complete your source subjects.
completeMission() {
this.missionAnnouncedSource.complete();
this.missionConfirmedSource.complete();
}
and call it when you wan't
onOtherClick() {
this.service.completeMission();
}
Upvotes: 3