AngularFire2 上传多个文件并获取下载 URls 的数组



我想上传多个文件,然后使用 angularFire2 返回数组中的相对 URL,为此我在服务文件中创建了一个 Observable 列表,然后在组件上使用combineLatest()订阅了它,但我无法得到结果。由于downloadURL()在任务上不再可用,我正在努力返回最终结果数组。

聊天服务网

uploadMessageFiles(filesList, roomId: string) {
const downloadUrls$ = filesList.map((file) => {
let fileName = this.db.createPushId();
fileName+= file.name;
const filePath = `/chat-files/${roomId}/${fileName}`;
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);

return task.snapshotChanges().pipe(
// missing logic
);
});
return downloadUrls$;
}

chat.component.ts

let dowloadObservable = this.chatService.uploadMessageFiles(
this.selectedFiles,
this.selectedRoom.id
);
combineLatest(...dowloadObservable).subscribe((downloadURLs) => {
//get URLs
});

我需要订阅并获得组件的结果,因为我那里有其他逻辑,我无法通过直接订阅来处理数据task.snapshotChanges()我相信获取下载 URL 的最简单方法是:task.snapshotChanges().pipe( finalize(() => downloadURL = this.storage.ref(path).getDownloadURL() ) ) .subscribe()但是我无法设法返回 URL 作为使用最终化和管道的可观察 susbcription 的结果。

我不熟悉 firebase,所以这可能需要稍微调整,因为我无法从您的代码中分辨出返回可观察量与静态数据的位置; 但在这里...

您可以让它返回一个包含所有单独上传结果的数组,而不是让uploadMessageFiles返回一个可观察量数组(稍后需要合并(,该数组发出一个数组,其中包含所有单个上传的结果。

from将创建一个可观察量,该可观察量从数组中发出每个项目。然后,可以使用mergeMap运算符对每个文件进行服务调用并发出其结果。最后,您可以使用scan运算符将所有排放合并到一个数组中。

这样的事情可以工作:

public uploadMessageFiles(filesList, roomId: string) {
return from(filesList).pipe(
mergeMap(file => {
const fileName = this.db.createPushId() + file.name;
const filePath = `/chat-files/${roomId}/${fileName}`;
const fileRef = this.storage.ref(filePath);
const task = this.storage.upload(filePath, file);
return task.snapshotChanges();
}),
map(changes => // return url from changes //),
scan((allUrls, url) => [...allUrls, url], [])
);
}

这是一个简化示例的 StackBlitz。

最新更新