angular - 中间带有 IF 语句的 RxJS 管道链接
问题描述
我得到一个值,并根据返回值,如果数据在我第一次发送并继续发送时实际返回,否则如果没有返回值,我将获得默认值并继续处理数据。
我的问题是在 IF 语句之后返回默认数据。我无法让它返回数据,而不是可观察/订阅
它看起来像这样:
getValuesFunction() {
const getFirstValues$ = this.ApiCall.getFirstValues();
this.subscription = getFirstValues$.pipe(
map(data => {
if (data.length === 0) {
// this line is the one I have a problem with
return this.processedStockApi.getDefaultValues().subscribe();
} else {
// this line returns fine
return data;
}
}),
switchMap(data => this.apiCall.doSomethingWithData(data))
).subscribe();
}
// ApiCall
getDefaultValues() {
return this.http.get<any>(this.stockUrl + 'getSelectiveDeleteData');
}
解决方案
map
与其使用与 Observable 一起使用的变体之一,例如or concatMap
(mergeMap
在switchMap
这种情况下也可以使用):
getFirstValues$.pipe(
concatMap(data => {
if (data.length === 0) {
// this line is the one I have a problem with
return this.processedStockApi.getDefaultValues();
} else {
// this line returns fine
return of(data);
}
}),
switchMap(data => this.apiCall.doSomethingWithData(data)),
).subscribe(...);
请注意,这两个if-else
块现在都返回 Observables。是concatMap
谁订阅它们并进一步发布它们的结果。
推荐阅读
- flutter - 如何在导航到下一个屏幕之前让启动屏幕等待计算?
- android - onItemClick 的查看器初始化不起作用
- python - 在数据框中打印计数
- .net-core - 有没有办法在 .Net Core 中更改 AWS Lambda 中的日志级别?
- javascript - 即使在异步控制台中正确获取 API 后,也无法读取未定义的属性“地图”
- python-3.x - 使用python根据条件选择两个或多个连续行
- objective-c - 无法连接到界面内的 ui 视图
- ubuntu - 通过 ssh 进入远程机器时保持 ZSH 配置
- javascript - 在 Firebase 查询中返回 UID
- java - 在 Java 中选择和替换随机生成的字母