Home > Enterprise >  Angular how to return an async value in function
Angular how to return an async value in function

Time:07-21

So I implemented a canDeactivate function which expects an observable of type boolean to be returned. Condition to leave is async so I can't do something like this for example:

public canDeactivate(): Observable<boolean> {
    setTimeout(() => {
        return of(true);
    }, 5000);
}

How can I make a request inside this function that will determine if I can leave or not?

CodePudding user response:

Use native rxjs for that, no need for timeouts

public canDeactivate(): Observable<boolean> {
    return interval(5000).pipe(take(1),mapTo(true));
}

or

public canDeactivate(): Observable<boolean> {
  return of(true).pipe(delay(5000);
}

CodePudding user response:

You can do it like this.

public canDeactivate(): Observable<boolean> {
  return new Observable<boolean>( observer => {
    setTimeout( () => {
      observer.next(true);
    }, 5000);
  });
}

CodePudding user response:

You can create an Observable instance and return it

return new Observable(obs=>{
 setTimeout(() => {
        return obs.next(true);
    }, 5000);
)}

https://rxjs.dev/guide/observable

  • Related