angular - Angular 多个订阅然后执行操作
问题描述
我有一个使用订阅从 API 请求数据的函数。我正在尝试重新编写它,以便在所有 API 调用完成后返回一个布尔值。有没有更好的方法来写这个?
我当前的代码:
public res1=null;
public res2=null;
getData(){
this.svc.getData1().subscribe(x={this.res1=x;})
this.svc.getData2().subscribe(x={this.res2=x;})
}
我正在考虑尝试创建一个 Observable 来监听嵌套订阅的更改:(未经测试的代码!)
getData(): Observable<boolean>{
this.svc.getData1().subscribe(x=>{
this.res1=x;
this.svc.getData2().subscribe(x=>{this.res2=x;
return true;
})
})
)
}
解决方案
一种方法是使用 combineLatest。当所有可观察对象都发出一个值时,Combine latest 会发出一个值。
combineLatest(observeable1$, observable2$).subscribe(
// when both have submitted a value. return what you like.
);
如果你的 observable 只会解决一次。您也可以使用 forkJoin。这类似于 promise.All
推荐阅读
- javascript - 光滑滑块内的引导模态
- typescript - 正确输入 Box 类
- xml - XML 源的问题
- javascript - 自定义 HTML 元素不会切换 CSS 焦点伪类
- python - raise ImportError('Could not import PIL.Image.' '使用`array_to_img`需要PIL。')
- spring-batch - 如何在 Spring Batch 中处理相同的对象事实多个步骤?
- git - 给定标签的 git 子模块状态
- c# - WPF 文本框焦点()
- css - 将鼠标悬停在子菜单上时保持父菜单突出显示
- powershell - 在 PowerShell 中将环境变量设置为空字符串