0
votes

I keep having this issue and I don't think my approach is best and would appreciate some help.

I have a function return an observable that won't be available until some time (user clicks modal button, http calls finish, etc.). Let's say I want to display a confirmation modal and either proceed or return from the function depending on what the user selects. (note: the modal returns a promise)

doWork = () => {
  openConfirm().subsribe(res => {
    if (!res) { return };   // return from function if user selects 'No'
    
    // else proceed
  });
}

here is where I think I am returning the observable wrong using from

openConfirm = (): Observable<any> => {

  // ng bootstrap modal asking "Would you like to proceed" with a yes or no button 
  let modalRef = this.modalService.open(ConfirmModalComponent, {});


 return from(modalRef.result.then(res => {
        return true;  // Yes button
      }, () => { 
        return false;  // No button
      }));
  }
}

I want the observable to wait until the user selects yes or no on the modal before returning. as it is in my case. But is there a cleaner way? if I remove the from() operator and return of(true) or of(false) I get an error that I can't subscribe to undefined.

1
Is defer() what you're looking for? - martin
@martin not quite, sometimes I subscribe to observables and the data isn't ready to be returned right away, like in this example the modal click), and I either get subscribe errors or have to do use this ugly from() code or of() if its not a promise. - brett

1 Answers

1
votes

I am not certain but try this using the from operator like you have 1.

doWork = () => {
  openConfirm().subsribe(res => {
    // promise was a success - Yes clicked
  }, err => { // error callback of subscribe
    // promise was a failure - No clicked
  });
}
.....
openConfirm = (): Observable<any> => {

  // ng bootstrap modal asking "Would you like to proceed" with a yes or no button 
  let modalRef = this.modalService.open(ConfirmModalComponent, {});


   return from(modalRef.result)
  }
}

See if you can take advantage of just returning from(Promise) and subscribing to this promise and seeing if the observable funnels properly to the success callback and error callbacks.