Ivilin Stoyanov
Ivilin Stoyanov

Reputation: 407

How to pass functions dynamically to angular forkJoin()?

I'm passing to the sources array two functions dynamically, but I'm having a problem when only one function is being passed.

How to mock empty observable, so if the second function is passed to not have it mapped with a, but with b.

 let sources = [];
    if (!isNullOrUndefined(email_address)) {
      sources.push(this.commonService.lookUpEmailAddress(emailParameters));
    }
    if (!isNullOrUndefined(telephone_number)) {
      sources.push(this.commonService.lookUpTelephoneNumber(telephoneParameters));
    }
   
    forkJoin(...sources)
      .subscribe(
      ([a, b]) => { // do stuff here }
    

Upvotes: 1

Views: 1361

Answers (2)

Barremian
Barremian

Reputation: 31125

You could pass a variable that holds the array, instead of an explicit array [a, b]. Try the following

forkJoin(...sources).subscribe(
  (response) => { 
    // response[0] - a - result from 1st observable in sources
    // response[1] - b - result from 2nd observable in sources (don't access response[1] if there is no 2nd observable)
  }
);

Now you could access the elements of the result that you know exist. For eg. response[1] is undefined if there is no 2nd element in the sources array.

Upvotes: 0

Eliseo
Eliseo

Reputation: 57939

you can always has two observables, some like

sources=[
!isNullOrUndefined(email_address)?
          this.commonService.lookUpEmailAddress(emailParameters):
          of(null),
!isNullOrUndefined(telephone_number)?
          this.commonService.lookUpTelephoneNumber(telephoneParameters):
          of(null)
]

Then in subscribe check if a==null or b==null

Upvotes: 1

Related Questions