此方法中有两个POST请求:
public createArticle(request: IArticle) {
const requestPath = `${this.backendUrl}/articles`;
return this.http
.post<IResponse<IArticleApiContract>>(requestPath, getArticleApiContract(request), {
headers: this.headers
})
.pipe(map(processResponseItem))
.pipe(map(responseItem => getArticlesModel(responseItem)))
.pipe(
map(article => {
if (request.uploads) {
const uploadPath = `${this.backendUrl}/articles/${article.id}/files`;
const formData = new FormData();
request.uploads.forEach(file => {
formData.append('fileData', file);
});
this.http
.post<IResponse<IFileApiContract>>(uploadPath, formData, {
headers: this.headers
})
.toPromise();
}
return article;
})
);
}
第一个创建文章,第二个将一些文件上传到该文章。上传请求完成后,如何才能返回Observable<IArticle>
?因为此可观察对象具有字段isCreated
,所以我在提交后使用它来关闭模式窗口。但是现在在上传完成之前,我收到了可观察到的信息。
您可以使用mergeMap()解决您的问题。
public createArticle(request: IArticle) {
const requestPath = `${this.backendUrl}/articles`;
return this.http
.post<IResponse<IArticleApiContract>>(requestPath, getArticleApiContract(request), {
headers: this.headers
})
.pipe(
map(processResponseItem),
map(responseItem => getArticlesModel(responseItem)),
mergeMmap(article => {
if (request.uploads) {
const uploadPath = `${this.backendUrl}/articles/${article.id}/files`;
const formData = new FormData();
request.uploads.forEach(file => {
formData.append('fileData', file);
});
return this.http.post<IResponse<IFileApiContract>>(uploadPath, formData, {headers: this.headers}).pipe(map(() => article))
}
return of(article);
})
)
}