[英]Angular 2 - CanActivate undefined value
我的CanActivate()函数有问题,因为变量令牌未收到函数verifytoken的响应始终返回未定义,如何解决此问题?
码
private verifytoken()
{
if(this._functionservice.getCookie("Cookie") != '' && this._functionservice.getCookie("Cookie") != "undefined")
{
this._symfonyservice.validtoken().subscribe(
data => {this.resut = data;
if(this.resut['is_valid']==true)
{
console.log('true');
return true;
}
else
{
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
},
error =>{
alert("Sessão Expirada");
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
);
}
else{
this.router.navigate(['login']);
return false;
}
}
canActivate() {
let token = this.verifytoken();
console.log(token);
return token;
}
我在这里发现2个问题:
private verifytoken()
{
if(this._functionservice.getCookie("Cookie") != '' && this._functionservice.getCookie("Cookie") != "undefined")
{
// 1 - You are returning nothing here, only inside the subscriptions. So, you wont be able to get any data if you get inside this if statement
this._symfonyservice.validtoken().subscribe(
data => {this.resut = data;
if(this.resut['is_valid']==true)
{
console.log('true');
return true;
}
else
{
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
},
error =>{
alert("Sessão Expirada");
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
);
}
else{
// 2 - you are navigating to another place, so you wont be able to get any data from here
this.router.navigate(['login']);
return false;
}
}
canActivate() {
let token = this.verifytoken();
console.log(token);
return token;
}
因此,您必须在if语句中返回预订,否则将无法获取任何数据。
---编辑---回答问题:
许可返回许可,因此,可以在调用方法之后调用订阅。
在verifytoken()
您必须返回该canActivate()
,然后在canActivate()
您必须像我在下面那样订阅该canActivate()
或同步等待该值:
private verifytoken(){
if(this._functionservice.getCookie("Cookie") != '' && this._functionservice.getCookie("Cookie") != "undefined")
{
// here I returned the promisse
return this._symfonyservice.validtoken().subscribe(
data => {
this.resut = data;
if(this.resut['is_valid']==true){
console.log('true');
return true;
}
else
{
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
},
error =>{
alert("Sessão Expirada");
this._functionservice.deleteCookie("Cookie");
console.log('false');
this.router.navigate(['login']);
return false;
}
);
}
else{
this.router.navigate(['login']);
return false;
}
}
这里有个窍门。 您不能从promisse函数内部返回函数canActivate(),因为它的作用域是。 因此,您有2个选择:
1-(异步)是在调用canActivate的地方调用被许可人,然后从那里调用更改。
canActivate() {
return this.verifytoken();
}
2-(sync)会花一些时间来检测何时触发了触发和将响应分配给令牌变量,因此您可以将其返回
canActivate() {
var token = this.verifytoken();
while(token == undefined){
// wait until token has been set
}
return token;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.