Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Auth Guard with a Promise and if statement

I want to use a guard to decide whether or not a user can navigate to the login pag, but I know my logic is faulty because of a Promise. See my code below.

  canActivate(): boolean | Observable<boolean> | Promise<boolean> {
    if (!this.localStorage.getObject('isInitialized')) {
      this.router.navigate(['/locaties']);
      return true;
    }
    return false;
  }

I know what I'm doing is wrong, but I'm lacking the knowledge about promises to go around this. What do I need to do to make this work?

This is my localstorage.getObject():

  // Returns object
  async getObject(key: string) {
    const ret = await Storage.get({ key: key });
    return JSON.parse(ret.value);
  }
like image 404
Furkan Öztürk Avatar asked Oct 30 '25 02:10

Furkan Öztürk


1 Answers

If you want to use an async result based condition in your can activate method then you can use Promise. If you intend to use a direct value from the local storage then you need not use promise. You can do something like below to use promise...

canActivate(): Promise<boolean> {
  return new Promise((resolve) => {
    if (!this.localStorage.getObject('isInitialized')) {
      this.router.navigate(['/locaties']);
      // Do not allow the route
      resolve(false);
    } else {
      // Allow the route
      resolve(true);
    }
  });
}
like image 162
Sai Hemanth Talasila Avatar answered Nov 01 '25 16:11

Sai Hemanth Talasila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!