订阅Angular 2中的多个Observable
发布时间:2020-12-17 07:34:53 所属栏目:安全 来源:网络整理
导读:我的Angular 2应用程序在服务中有2个方法[GetCategories()和GetCartItems()],这两个方法都返回 观测. 为了从我的组件一个接一个地调用这两个方法,我写了下面的代码 ngOnInit() { this.appService.GetCategories().subscribe( (data) = { this.appService.cat
我的Angular 2应用程序在服务中有2个方法[GetCategories()和GetCartItems()],这两个方法都返回
观测. 为了从我的组件一个接一个地调用这两个方法,我写了下面的代码 ngOnInit() { this.appService.GetCategories().subscribe( (data) => { this.appService.categories = data; this.appService.GetCartItems().subscribe( { next: (data) => { this.appService.cart = data},error: (err) => { this.toaster.error('cart==>' + err)} }) }); } 基本上从GetCategories()的订阅中调用GetCartItems,我觉得这不是正确的方法,这是一种回调地狱. 任何想法如何以更好的方式实现这一点(比如在promises中链接“then”)?
看起来GetCartItems不依赖于GetCategories.然后你可以使用
zip:
Observable .zip( this.appService.GetCategories() this.appService.GetCartItems() ) .catch(err => this.toaster.error(err)) .subscribe(([categories,cartItems]) => { this.appService.categories = categories; this.appService.cart = cartItems; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 【WebService】CXF处理javaBean等复合类型以及Ma
- 异步 – Angular2 – 在路由更改时停止’setInte
- scala – Selfreferencing Generics
- $watch How the $apply Runs a $digest
- angular – 从’rxjs / Observable’导入{Observ
- angularjs-$interval 服务
- Bootstrap3基础 warning/active... 表格的状态类
- B中的Bash输入/输出
- atlas学习系列之二(AutoCompleteExtender篇)
- unix – 如何在-exec中使用管道查找
热点阅读