RxJS 返回空承诺但继续链

Jon*_*man 3 promise observable rxjs angular

我有一个 http 服务,我需要根据用户输入来调用它。

saveImage(): Observable<Photo> {
    if (!this.squaredImage) {
        return Observable.of();
    }

    this.photoCreateDto = {
        sourcePhoto: this.sourceImage,
        squaredPhoto: this.squaredImage,
        fileExtension: this.fileExtension
    };

    return this.photoService.createPhoto(this.photoCreateDto);
}
Run Code Online (Sandbox Code Playgroud)

saveImage从另一个保存函数调用:

save() {
    this.saveImage().subscribe((newPhoto: Photo) => {

         .. never gets here

    });
}
Run Code Online (Sandbox Code Playgroud)

如果this.squaredImage没有值并且返回空承诺,则链结束。如果createPhoto调用该服务,它将继续。我也尝试过返回Observable.empty()。rxjs 中如何处理这种情况?

mar*_*tin 5

问题是您只处理通知next

this.saveImage().subscribe((newPhoto: Photo) => { ... });
Run Code Online (Sandbox Code Playgroud)

...同时Observable.of()Observable.empty()不发出任何信号next(它们只是发送complete通知)。

因此,您可以做的一件事是发出例如null,然后在订阅者中检查您发送的值:

saveImage(): Observable<Photo> {
    if (!this.squaredImage) {
        return Observable.of(null);
    }
    ...
}

...

this.saveImage().subscribe((newPhoto: Photo) => {
    if (newPhoto === null) {
        // ...
    }

    // ...
})
Run Code Online (Sandbox Code Playgroud)

或者您可以同时收听nextcomplete通知(但请注意,当您返回时,也可能会发送通知)this.photoService.createPhotocomplete

this.saveImage().subscribe({
  next: (newPhoto: Photo) => {...}
  complete: () => { ... }
})
Run Code Online (Sandbox Code Playgroud)