gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:11:52 27 4
gpt4 key购买 nike

我有一个使用 Firebase Storage 发送一些图像数据的应用程序,因此我使用此方法:

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: Observable;

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

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

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

(3) [UploadTaskSnapshot, UploadTaskSnapshot, UploadTaskSnapshot]

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

最佳答案

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

关于javascript - 为什么 forkJoin 从我的可观察量中返回错误的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59532740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com