Gregor A
Gregor A

Reputation: 237

Angular how to return an async value in function

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?

Upvotes: 0

Views: 76

Answers (3)

Antoniossss
Antoniossss

Reputation: 32535

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);
}

Upvotes: 2

Fan Cheung
Fan Cheung

Reputation: 11370

You can create an Observable instance and return it

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

https://rxjs.dev/guide/observable

Upvotes: 1

N.F.
N.F.

Reputation: 4192

You can do it like this.

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

Upvotes: 1

Related Questions