如何获得在canActivate上进行验证的承诺的值



我需要得到返回this.isJwtValid()的值,但目前它没有返回promise的结果的值,代码继续其流程而不停止,我需要在以下行中得到该promise的结果:

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

继续我的逻辑。

我该怎么做?

这是我的代码:

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可以返回Promise或Observable或Value,所以你可以这样做。

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也可以返回promise。因此可以使用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;
}
}
``

最新更新