angulartypescriptrxjsfork-join

forkJoin nor combineLatest from rxjs doesn't call api services


I'm trying to pass api calls inside the forkJoin or combineLatest then pipe them and finally map the results one by one to asign them values to the class level variables.

All the api calls return an observable


operator: any;
field: any;
value: any;
canonicalFields: any;
 
ngOnInit(): void {
 combineLatest([
 this.api.getoperators(),
 this.api.getFields(),
 this.api.getValues(),
 this.api.getCanonicalFields()])
 .pipe(
   map(([op, fi,va, can]) => {
    this.operator = op;
    this.field = fi;
    this.value = va;
    this.canonicalFields = can;
    console.log(op,fi,va,can);
   }));
}

Solution

  • This is normal behavior, assuming you are using the Angular HTTP client.

    The Angular HTTP client API creates cold Observables. That means no request will be sent as long as there is no subscription to the source.

    The combineLatest and map operators don't subscribe to the source. They just create new Observables that are still cold as long as their source(s) are cold.

    Instead of the the pipe + map, try to call subscribe on the return value of combineLatest. This should trigger sending the requests.

    E.g.:

    combineLatest([...])
       .subscribe(([op, fi,va, can]) => { ... }));
    

    Word of caution: You should ensure your subscriptions are eventually unsubscribed or you may end up with memory leaks! The best way to deal with this is to not subscribe Observables directly, but expose them to the template using the async pipe. This way, Angular will manage the subscription lifetime for you.