1

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 }
    

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I tried this, but it didn't work, because the second function is going to the [0] of the array, so it's not mapped correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.