0

How can I write a function to wait for the return value using rxjs? I want to show the confirm dialog only if MyString is not empty

My code is as below

private showConfirmation(): boolean{
    let confirmResponse = false;
    if( this.MyString!== '' ) {
        this.alertService.confirm( 'Confirm', this.MyString + 'Are you sure you want to proceed?' ).pipe(
            take(1),
            filter( confirm =>  !!confirm),
            tap(value => {
                confirmResponse = true;
            }),
        ).subscribe();
    }
    return confirmResponse;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
user2837961
  • 1,505
  • 3
  • 27
  • 67
  • You should probably be returning an `Observable` not using `tap` and subscribe to that upstream but that depends on what's calling this code. – Liam Aug 24 '21 at 11:30

1 Answers1

0

Your thinking about it wrong. You should be treating your data as a stream that is consumed higher up. It's hard to be explicit and I would recommend you read How do I return the response from an Observable/http/async call in angular?. But I would probably change your code to:

import { of, Observable } from 'rxjs';
import { take, switchMap } from 'rxjs/operators';


private showConfirmation(): Observable<boolean>{

    if( this.MyString!== '' ) {
        return this.alertService.confirm( 'Confirm', this.MyString + 'Are you sure you want to proceed?' ).pipe(
            take(1),
            switchMap( confirm =>  !!confirm)
        );
    }
    return of(false);
}

and then whatever is calling this should subscribe to it, possibly using the async pipe:

<p>{{showConfirmation() | async}}</p>
Liam
  • 27,717
  • 28
  • 128
  • 190