简体   繁体   中英

how can I get the value of a promise to do the validation on the canActivate?

I need to get the value that returns this.isJwtValid() but currently it is not returning the value of the result of the promise , the code continues its flow without stopping there, and I need to get the result of this promise in this line:

let token = this.isJwtValid() //I need get the value of the promise in this line

to continue with my logic.

how can I do it?

this is my code:

export class verificarToken implements CanActivate {
  constructor(private router: Router, private storage: Storage) {}

  async isJwtValid() {
    const jwtToken: any = await this.storage.get("token");
    console.log(jwtToken); /// this is showed second
    if (jwtToken) {
      try {
        return JSON.parse(atob(jwtToken.split(".")[1]));
      } catch (e) {
        return false;
      }
    }
    return false;
  }

  canActivate(ruta: ActivatedRouteSnapshot, estado: RouterStateSnapshot) {

    let token = this.isJwtValid(); //I need get the value of token here
    if(token) {
      console.log(token) // this is showed first
      if (ruta.routeConfig.path == "login") {
        this.router.navigate(["/tabs/tab1"]);
      }
      return true;
    }
    this.storage.clear();
    this.router.navigate(["/login"]);
    return false;
  }
}

CanActivate can returns a Promise or Observable or Value, so you can do it like this.


canActivate(ruta: ActivatedRouteSnapshot, estado: RouterStateSnapshot) {

    return this.isJwtValid().then(token => {

            if (token) {
                console.log(token) // this is showed first
                if (ruta.routeConfig.path == "login") {
                    this.router.navigate(["/tabs/tab1"]);

                    return true;
                }
                this.storage.clear();
                this.router.navigate(["/login"]);
                return false;
            });
    }
}

canActivate can return promise as well. hence make use of async/await.

async canActivate(ruta: ActivatedRouteSnapshot, estado: RouterStateSnapshot) {

    let token = await this.isJwtValid(); //I need get the value of token here
    if(token) {
      console.log(token) // this is showed first
      if (ruta.routeConfig.path == "login") {
        this.router.navigate(["/tabs/tab1"]);
      }
      return true;
    }
    this.storage.clear();
    this.router.navigate(["/login"]);
    return false;
  }
}
``

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM