Rohit
Rohit

Reputation: 3136

Can't get forkJoin to fire

I'm building a guard in Angular where I need to make two different HTTP requests, and based on both, determine whether to proceed or not. I noticed forkJoin is the right way to do this, but I can't get mine to fire.

In my code, I have:

this.userService.watchCurrentUser().subscribe(data => { console.log(data) });
this.orgService.watchOrg().subscribe(data => { console.log(data) });
Observable.forkJoin(
    this.userService.watchCurrentUser(),
    this.orgService.watchOrg()
).subscribe(data => {
    console.log(data);
});

The first two subscriptions were added later to test if the calls were actually firing, and they are; I see the logs from them. But I never see a lot from the forkJoin.

I import it at top of my file:

import { Observable, BehaviorSubject } from 'rxjs/Rx';
import 'rxjs/add/observable/forkJoin';

Is there something else I'm missing in order to use forkJoin?

Upvotes: 3

Views: 798

Answers (2)

Fernando F.
Fernando F.

Reputation: 1

In your case, a guard, you just need one result of each stream. Thus, you should this:

Observable.forkJoin(
    this.userService.watchCurrentUser().first(),
    this.orgService.watchOrg().first()
).map(data => {
    let permitted: boolean;
    // check the data you want to.
    return permitted; 
});

In the code above the fork is combining the first result of two observables, and both results will be mapped to a boolean.

Upvotes: 0

martin
martin

Reputation: 96891

Observable.forkJoin() requires all source Observables to emit at least one item and to complete.

Are you sure both of your source Observables complete?

If they don't (and based on their internal logic they can't) maybe you'd rather use zip() or combineLatest().

Upvotes: 3

Related Questions