Angular 6嵌套HTTP调用嵌套调用从不执行



在Angular 6中工作时,我有两个HTTP调用需要串行执行。第一个调用成功,第二个调用表示成功,但从未实际发出HTTP请求。

如果我分解这两个调用并分别执行它们,它们都可以工作。然而,当将它们串联在一起时,第二次调用永远不会起作用。

这里的一般想法是从服务器请求一个签名的URL,并在收到后将文件上传到指定的URL。

export class StaticAssetService {
constructor(private httpClient: HttpClient) { }
public uploadAsset(assetType: StaticAssetType, file: File): Observable<any> {
if (file) {
return this.httpClient.get(`${environment.apiURI}/secure/file-upload/getPresignedURLForUpload.json`, {
params: {
assetType: assetType,
originalFileName: file.name
}
}).pipe(map(response => {
return this.httpClient.put(response.signedURL, file, {
headers: new HttpHeaders({'Content-Type': file.type}),
reportProgress: true
})
}));
}
}
}

不建议使用上面显示的语法嵌套HTTP调用。相反,有一些特定的RxJS操作符(类似于map(专门用于串行执行HTTP调用。

评论者推荐的switchMap就是其中之一。这里有一个例子:

Angular4-嵌套Http调用

以下是一些可能有用的文章:

https://medium.com/@juliapassynkova/switchmap-in-details-b98d34145311

https://blog.angular-university.io/rxjs-higher-order-mapping/

最新更新