Angular 我如何才能获得在canActivate上进行验证的承诺的价值?
我需要获取返回的值Angular 我如何才能获得在canActivate上进行验证的承诺的价值?,angular,angular-routing,angular-router-guards,Angular,Angular Routing,Angular Router Guards,我需要获取返回的值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(p
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可以返回承诺、可观察或价值, 所以你可以这样做
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也可以回报承诺。因此,请使用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;
}
}
``