Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何等待可观察的循环_Angular_Typescript - Fatal编程技术网

Angular 如何等待可观察的循环

Angular 如何等待可观察的循环,angular,typescript,Angular,Typescript,在我的应用程序中,我必须先上传一个图像循环,才能从系统中获取文件ID。 在我得到ID后,我可以上传对象 async uploadFiles(token: string):Promise<number[]> { let ids = Array<number>(); this.images.forEach((image: ImageData) => { this.fileService.uploadFile(image, token).sub

在我的应用程序中,我必须先上传一个图像循环,才能从系统中获取文件ID。 在我得到ID后,我可以上传对象

async uploadFiles(token: string):Promise<number[]> {
    let ids = Array<number>();
    this.images.forEach((image: ImageData) => {
      this.fileService.uploadFile(image, token).subscribe((result: File) => {
        ids.push(result.data.id);
      })
    });
    return ids;
  }
异步上传文件(令牌:字符串):承诺{ 设ids=Array(); this.images.forEach((image:ImageData)=>{ this.fileService.uploadFile(图像、令牌).subscribe((结果:文件)=>{ 推送(result.data.id); }) }); 返回ID; }
此函数的目标是返回所有ID。但是,由于fileService有一个subscribe,它将只返回一个空数组。

这里的问题是,当您执行fileService.uploadFile.subscribe()时,此订阅是异步执行的。订阅将等待,直到获得结果,同时在订阅后立即执行行。因此,在订阅之后立即执行返回ID。在这一点上,结果没有任何值,也没有任何内容被推送到ids中。所以,它只返回空数组

您可以全局声明ID。因此,当结果准备好时,您可以将其推入,并可以使用ID,或者您可以使this函数返回一个可观察的值,并使用subjects来提供值。它显示在下面的代码中

private idsSubject = new Subject<number[]>();

async uploadFiles(token: string):Observable<number[]> {  //made return type observable
    this.images.forEach((image: ImageData) => {
      this.fileService.uploadFile(image, token).subscribe((result: File) => {
        this.idsSubject.next(result.data.id);
      })
    });
    return this.idsSubject.asObservable();
  }
private idsSubject=新主题();
异步上载文件(标记:字符串):可观察{//使返回类型可观察
this.images.forEach((image:ImageData)=>{
this.fileService.uploadFile(图像、令牌).subscribe((结果:文件)=>{
this.idsSubject.next(result.data.id);
})
});
返回此.idsSubject.asObservable();
}
当您希望ids订阅此功能时。像uploadFiles(“我的字符串”).subscribe((id)=>this.ids.push(id))
试试这个,希望有帮助。否则告诉我

您必须返回Observable并使用switchMap进行调用第二个Api上载。

这是否回答了您的问题?基本上,你不能那样做。您需要获取forEach函数的其他参数(索引、数组),并使用这些参数查看您是否在images数组中的最后一个图像上,然后使用ID解析您的承诺。@HereticsMonkey是否可以将this.fileService设置为其他函数并将其作为承诺(异步)返回然后在forEach中等待?您可以尝试添加
.toPromise()
,而不是
。订阅(…)
,然后等待。您最好在
fileService
上创建一个
uploadFiles
方法,该方法接受
this.images
。使该方法一次上载多个文件并返回多个ID。根据服务基础设施的不同,这可能简单,也可能困难,但比在短时间内发出许多请求更有效。