23

Using this code:

this.router.navigateByUrl('/login');

I get the following warning: promise returned from navigatebyurl is ignored. How and when would I want to handle the promise here?

P.S. I'm using this in AuthGuard's canActivate.

Sammy
  • 3,395
  • 7
  • 49
  • 95
  • 4
    If you are not interested in knowing when that navigation completed, then indeed you don't need to do anything with that promise. If this warning is from IntelliJ, you [can get rid of the warning](http://stackoverflow.com/a/41279095/5459839). NB: It seems odd to trigger a navigation within `canActivate`, which is intended only to return a boolean. I don't think adding such side-effects are good practice. – trincot May 20 '17 at 18:47
  • Thanks for the NB! What would you do, then, if you want to forward the user to a login page if they're not authenticated? – Sammy May 20 '17 at 18:49
  • On second thought, it seems that is the way it is done, so forget what I said in my NB. Remains the warning you get: you can ignore it, since you don't need/want to do anything once that promise resolves. – trincot May 20 '17 at 19:05
  • Actually, I do! I would like to display a spinner before `canActivate` starts and remove it after it completes, since I do have an http request within that may take some time! – Sammy May 20 '17 at 19:09
  • 6
    In that case put the code to remove the spinner in the `then` callback. Something like: `this.router.navigateByUrl('/login').then(_ => { removeSpinner(); });` – trincot May 20 '17 at 19:11

1 Answers1

10

The navigateByUrl function returns a promise so you can use .then() method :

this.router.navigateByUrl('/login').then(() => {
    // Do something 
});
Amir BenAmara
  • 676
  • 7
  • 12
  • 1
    That is certainly a solution, but what if I want just to make the navigation? Should I just call the `this.router.navigateByUrl('/login').then()` to get rid of the warning? I do not want to add async/await as it would move the warning to the caller (who might not expect async call). – Felix Sep 08 '22 at 08:10
  • 1
    Here (https://stackoverflow.com/a/64234381/1662819) is another answer, I like better, which goes beyond the obvious – Bahaa Oct 14 '22 at 21:28