Search code examples
angulartypescriptif-statementpromiseauth-guard

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

Solution

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