从 observable 的 finalize 方法返回一个 observable

Ara*_*ash 4 rxjs firebase angular

具体案例是这样的:AngularFirebase 文档说为了从上传的文件中获取下载 URL,你需要这样做:

const task = this.storage.upload(filePath, file);

// observe percentage changes
// get notified when the download URL is available
task.snapshotChanges().pipe(
    finalize(() => this.downloadURL = fileRef.getDownloadURL() )
 )
.subscribe();
}
Run Code Online (Sandbox Code Playgroud)

现在,我有一个上传方法,我想从中返回一个可观察的字符串。我的方法签名看起来像:

upload(file :File) :Observable<string> {

......

}
Run Code Online (Sandbox Code Playgroud)

我试过这样做:

return <Observable<string>>task.snapshotChanges().pipe(
        finalize(() => {
            const url = fileRef.getDownloadURL();
            console.log('download url is ',url);
            return url;
        })
    );
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为原始 observable 中还有其他类型快照更改的元素。

现在我的问题是,如何使用示例中的代码有效地返回我想要的类型

ggr*_*nig 5

如文档中所述,finalize...

返回一个镜像源 Observable 的 Observable,但是当源在完成或错误时终止时将调用指定的函数。

这意味着,您不能使用传递的函数更改 Observable 类型。

相反,您可以组合last运算符和map运算符来获取最后一个值的通知,映射到所需的属性。它看起来像这样:

return <Observable<string>>task.snapshotChanges().pipe(
        last(),
        map(() => {
            const url = fileRef.getDownloadURL();
            console.log('download url is ',url);
            return url;
        })
    );
Run Code Online (Sandbox Code Playgroud)