[英]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.