我有这样的服务方法:
updateUser(article) {
this.httpClient
.put(`articles/${article.id}`, article)
.pipe(
map(res => res.response),
mergeMap(updatedArticle =>
this.articlesTagsAPI.someMethod(updatedArticle.id).pipe(
map(tags => ({ ...updatedArticle, tags })),
article.articleType === 'news'
? mergeMap(() =>
this.articlesTagsAPI.someOtherMethod(updatedArticle.id, article.tags).pipe(
map(() => {
return {
...updatedArticle,
tags: article.tags
};
})
)
)
: null
)
)
);
}
如您所见-我正在尝试添加条件
mergeMap
(如果条件->调用其他方法)有可能做些什么吗?
因为返回null-不是最好的主意
如果条件无效,则应发生以下情况:
updateUser(article) {
this.httpClient
.put(`articles/${article.id}`, article)
.pipe(
map(res => res.response),
mergeMap(updatedArticle =>
this.articlesTagsAPI.someMethod(updatedArticle.id).pipe(
map(tags => ({ ...updatedArticle, tags }))
)
)
);
}
最佳答案
如该非常有用的article中所述,执行此操作的正确方法是添加of
指令,以始终在最终订阅中返回Observable的值。
尝试这个:
updateUser(article) {
this.httpClient
.put(`articles/${article.id}`, article)
.pipe(
map(res => res.response),
mergeMap(updatedArticle =>
this.articlesTagsAPI.someMethod(updatedArticle.id).pipe(
map(tags => ({ ...updatedArticle, tags })),
article.articleType === 'news'
? mergeMap(() =>
this.articlesTagsAPI.someOtherMethod(updatedArticle.id, article.tags).pipe(
map(() => {
return {
...updatedArticle,
tags: article.tags
};
})
)
)
: of(null)
)
)
);
}
关于javascript - RxJS:跳过条件的mergeMap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53705994/