在 subscribe() 完成时做一些事情

Do something when subscribe() completes

我在一个组件中有这段代码,我在控制台中看到的是这条消息:'from component 1: mission started'。所以它从服务中得到了正确的响应,但是一旦它完成我想打印消息 'successed!!' 而这从来没有发生过......当 subscribe() 完成时我该如何做?

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!!'));
}

这是我服务中的代码:

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);
    }
}

除非您这么说,否则 Observable 不会完成。

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');

输出:

value: a
value: b
value: c
completed

完成后d不会写入

因此,对于您的情况,您应该添加一个 completeMission() 函数来完成您的源主题。

completeMission() {
  this.missionAnnouncedSource.complete();
  this.missionConfirmedSource.complete();
}

在你不想的时候调用它

onOtherClick() {      
  this.service.completeMission();
}