Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 订阅多个可观察对象(如承诺中的chaining then())_Angular_Rxjs_Rxjs5 - Fatal编程技术网

Angular 订阅多个可观察对象(如承诺中的chaining then())

Angular 订阅多个可观察对象(如承诺中的chaining then()),angular,rxjs,rxjs5,Angular,Rxjs,Rxjs5,我的Angular 2应用程序在一个服务中有两个方法(GetCategories()和GetCartItems()),这两个方法都返回可观察的s 为了从我的组件中一个接一个地调用这两个方法,我编写了以下代码: ngOnInit() { this.appService.GetCategories().subscribe( (data) => { this.appService.categories = data; this.appService.Ge

我的Angular 2应用程序在一个服务中有两个方法(
GetCategories()
GetCartItems()
),这两个方法都返回
可观察的
s

为了从我的组件中一个接一个地调用这两个方法,我编写了以下代码:

 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()
subscribe()
中调用
GetCartItems()
,我觉得这不是正确的方法。这简直是地狱


关于如何以更好的方式实现这一点的任何想法(如在
Promise
s中链接
then()

看起来像
GetCartItems
并不依赖于
GetCategories
。然后您可以使用:


这通常是通过
concat()
concatMap()
或最终使用
concatAll()
完成的,具体取决于您的用例以及您是否需要按顺序调用这两个服务

function GetCategories() {
    return Observable.timer(1000).do(() => console.log('GetCategories()'));
}

function GetCartItems() {
    return Observable.timer(1000).do(() => console.log('GetCartItems()'));
}

console.log('start...');

GetCategories()
  .concatMap(() => GetCartItems())
  .subscribe(() => console.log('done'));
这将打印到控制台:

start...
GetCategories()
GetCartItems()
done
每个项目都会延迟,以显示它们是按顺序依次调用的

如果不需要保持相同的顺序,可以使用
merge()
mergeMap()

见现场演示:


请注意,使用
zip()
可能会有不希望的行为。请参见

我认为
可观察。CombineTest
是正确的选择,而不是
可观察。zip
(如果我理解问题的话)。自从你写这篇文章以来,这一年的情况可能发生了变化。当我使用
Observable.zip时,没有第三个参数(如上述情况),其中一个输入是未定义的,这取决于订阅何时触发。
start...
GetCategories()
GetCartItems()
done