Angular 2 - 同时运行 2 个订阅

The*_*eal 0 observable rxjs rxjs5 angular

我有以下代码:

//Subscription 3: role ID to role Name
        af.database.object('/roles/'+businessRole.$value)
        .subscribe((roleData) => {
        //Subscription 4: Get user info
        af.database.object('/users/'+businessRole.$key).subscribe(user => {
Run Code Online (Sandbox Code Playgroud)

其中包含订阅内的订阅。

这里的问题是应用程序在运行第二个之前等待第一个。我想一次执行它们,并获得每个的结果。我怎么能做到这一点?

我以前一直在使用Promise.All(),但是:

  1. 我很想知道如何用 rxjs 做到这一点
  2. 我找不到一种方法来获得每个可观察的结果 Promise.All()

谢谢

Ker*_*rla 5

我相信 Observable.forkJoin 正是您需要在您的情况下使用的。

这是您的代码使用 forkJoin 的样子:

Observable.forkJoin(
this.http.get('/roles/'+businessRole.$value).map((response: Response) => res.json()),
this.http.get('/users/'+businessRole.$key).map((response: Response) => res.json())
).subscribe(data => {
  data[0] // this will contain roleData
  data[1] // this will contain user
},
error => console.log(error));
Run Code Online (Sandbox Code Playgroud)

是一个有用的链接,您可以在其中了解有关 observable 以及如何使用 forkJoin 的更多信息。