gpt4 book ai didi

Angular 等待多个异步 post 请求,然后调用另一个端点

转载 作者:行者123 更新时间:2023-12-04 08:40:51 24 4
gpt4 key购买 nike

我正在使用 Angular 并希望实现以下功能。
在表单中,用户可以上传多张图片。在表单提交时,我想使用 post 方法调用上传端点,次数与图像一样多(简单的 for 循环)。每次调用都会返回一个响应,其中包含每个图像的谷歌云平台存储链接。每次我都会将链接推送到一个数组。一旦它遍历了所有图像,我想最终提交带有来自表单的 json 数据和带有谷歌云平台链接的数组的 post/patch 请求。
目前我正在努力处理异步代码。我想在最后调用的请求首先被触发,因此带有 GCP 链接的图像数组为空(事件虽然图像已正确上传到 GCP,但在保存文档后上传图像。来自类似的帖子 我知道可能会使用 switchMap 但我不知道如何在这种情况下使用它
#update 基于@Picci 评论,适用于一张图片
我必须将 FileList 转换为数组,我用

this.filesListArray = Array.from(this.filesList);
然后实现 Picci 解决方案:
 onSave(){
if(this.form.invalid) {
console.log(this.form)
return;
}

const uploadRequests$:Observable<[string]> = this.filesListArray.map(file =>
from(this.uploadService.upload(file)) // transform Promise to Observable using the rxjs 'from' function
.pipe(
map(response => response['filePath']),
catchError(err => of(`Error while uploading ${file}`)) // if there is an error, return the error
)
);

const urlsOrErrors$ = forkJoin(uploadRequests$);


urlsOrErrors$.pipe(
concatMap(result => this.eventsService.update(this.id, this.form.value, result))
).subscribe(() => {
this.form.reset();
this.router.navigate([this.id]);
})
.closed;
}

最佳答案

如果我理解正确,您首先要上传图像,然后保存一个 Json,其中包含与上传的图像对应的 url 列表等。
如果是这种情况,那么我会像这样继续下去。
首先我要转换 PromisesObservables并创建一个数组 Observables对应于上传文件的请求,类似这样

const uploadRequests$ = this.filesList.map(file => 
from(this.uploadService.upload(file)) // transform Promise to Observable using the rxjs 'from' function
.pipe(
map(response => response['filePath']),
catchError(err => of(`Error while uploading ${file}`)) // if there is an error, return the error
)
)
现在你有了一个 Observables 数组,你可以使用 forkJoin rxjs 的函数来创建一个 Observable,它将并行执行所有上传请求,并发出一个包含所有响应的数组。
考虑到我们构建 Observables 的方式,响应将是上传服务返回的 url 或错误字符串。
代码将类似于
const urlsOrErrors$ = forkJoin(uploadRequests$)
曾经 urlsOrErrors$发出,我们准备执行最后一个服务来保存 Json。我们需要确保只有在 urlsOrErrors$ 时才执行此类服务已经发出,所以我们使用 concatMap运算符(operator)。
最终的完整代码看起来像这样
const uploadRequests$ = this.filesList.map(file => 
from(this.uploadService.upload(file)) // transform Promise to Observable using the rxjs 'from' function
.pipe(
map(response => response['filePath']),
catchError(err => of(`Error while uploading ${file}`)) // if there is an error, return the error
)
)

const urlsOrErrors$ = forkJoin(uploadRequests$)

urlsOrErrors$.pipe(
concatMap(urlsOrErrors => this.eventsService.update(
this.id,
this.form.value,
urlsOrErrors
))
)
如果您对异步服务使用 rxjs 的常见模式感兴趣,您可能会发现 this article interesting .

关于Angular 等待多个异步 post 请求,然后调用另一个端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64577511/

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