为什么 forkJoin 从我的可观察量返回错误的值?



>我有一个使用 Firebase 存储发送一些图像数据的应用程序,所以我使用此方法:

startUpload() {
if (typeof this.fileList !== 'undefined' && this.fileList.length > 0) {
const observableList = [];
for (let i = 0; i < this.fileList.length; i++) {
// The storage path
const path = this.userModel.companyCode + `/${new Date().getTime()}_${this.fileList[i].name}`;
// Totally optional metadata
const customMetadata = {
app: 'My AngularFire-powered PWA!'
};
const fileRef = this.storage.ref(path);
// The main task
this.task = this.storage.upload(path, this.fileList[i], {
customMetadata
});
// Progress monitoring
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges();
// The file's download URL
observableList.push(
this.task.snapshotChanges().pipe(
finalize(async () => {
return await fileRef.getDownloadURL();
}))
);
// observableList = this.task.snapshotChanges();
// observableList.push(taskObservable);
}
console.log(observableList);
forkJoin(
observableList
).subscribe(
response => {
console.log(response);
}
);
}
}

这部分:

this.task.snapshotChanges().pipe(
finalize(async () => {
return await fileRef.getDownloadURL();
}))

当我单独使用这个函数并像这样使用时:

this.task.snapshotChanges().pipe(
finalize(async () => {
this.downloadUrl = await fileRef.getDownloadURL().toPromise;
}))

它们返回正确的URL,this.downloadUrl是一个全局变量,即downloadURL:可观察;

但是我不想一个接一个地返回我想要的 3 个结果,所以我有一个使用 forkJoin 的想法,它就像 javascript 中 promise 中的 Promise.All((:

console.log(observableList);
forkJoin(
observableList
).subscribe(
response => {
console.log(response);
}
);

我在控制台中得到了这个:

(3( [上传任务快照, 上传任务快照

, 上传任务快照]

如何从他们那里获取下载网址?

> finalize 采用返回类型 void 的回调函数。这就是为什么它适用于您的单独处理,但当您试图退回某些东西时则不然。 finalize-rxjs

我认为下面的代码应该适合你

startUpload() {
if (typeof this.fileList !== "undefined" && this.fileList.length > 0) {
const observableList = [];
const fileRefList = [];
this.fileList.forEach(file => {
const path =
this.userModel.companyCode + `/${new Date().getTime()}_${file.name}`; // Totally optional metadata
const customMetadata = { app: "My AngularFire-powered PWA!" };
fileRefList.push(this.storage.ref(path)); // The main task
this.task = this.storage.upload(path, file, {
customMetadata
}); // Progress monitoring
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges();
observableList.push(this.snapshot);
});
console.log(observableList);
forkJoin(observableList)
.pipe(map(async (_, i) => await fileRefList[i].getDownloadURL()))
.subscribe(response => console.log(response));
}
}

最新更新