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 中如何处理这种情况?
问题是您只处理通知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)
或者您可以同时收听next
和complete
通知(但请注意,当您返回时,也可能会发送通知)this.photoService.createPhoto
:complete
this.saveImage().subscribe({
next: (newPhoto: Photo) => {...}
complete: () => { ... }
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1323 次 |
最近记录: |