在 angular 中实施 canActivate auth guard
implementing canActivate auth guard in angular
我有一个具有此功能的服务,returns true 或 false on rather or not a token is valid
loggedIn() {
return this.http.get('http://localhost:3000/users/validateToken')
.map(res => res.json()).map(data => data.success);
}
我有一个 auth guard,可以在使用它的受保护路由上激活。
canActivate(){
this.authService.loggedIn().subscribe(res => {
if(res) {
return true;
}
else {
this.router.navigate(['/login'])
return false;
}
})
}
但是我得到这个错误。
incorrectly implements interface 'CanActivate'. Types of property
'canActivate' are incompatible.
Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean |
Promise | Obser...'.
Type 'void' is not assignable to type 'boolean | Promise | Observable'.
如何实现我在这里尝试做的事情?
canActivate
函数必须 return 布尔值、布尔值的承诺或布尔值的可观察值。
在你的情况下,你return什么都没有。可能是因为您在函数中省略了 return
。
但是,如果您添加它,它将不起作用,因为那样的话,您将 return 订阅,而签名不接受该订阅。
你可以这样做:
canActivate() {
return this.authService.loggedIn().map(res => {
if(!res) {
this.router.navigate(['/login']);
}
return res;
});
}
使用此代码,您遵守签名,并保持您的路由逻辑。
我有一个具有此功能的服务,returns true 或 false on rather or not a token is valid
loggedIn() {
return this.http.get('http://localhost:3000/users/validateToken')
.map(res => res.json()).map(data => data.success);
}
我有一个 auth guard,可以在使用它的受保护路由上激活。
canActivate(){
this.authService.loggedIn().subscribe(res => {
if(res) {
return true;
}
else {
this.router.navigate(['/login'])
return false;
}
})
}
但是我得到这个错误。
incorrectly implements interface 'CanActivate'. Types of property 'canActivate' are incompatible. Type '() => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Promise | Obser...'. Type 'void' is not assignable to type 'boolean | Promise | Observable'.
如何实现我在这里尝试做的事情?
canActivate
函数必须 return 布尔值、布尔值的承诺或布尔值的可观察值。
在你的情况下,你return什么都没有。可能是因为您在函数中省略了 return
。
但是,如果您添加它,它将不起作用,因为那样的话,您将 return 订阅,而签名不接受该订阅。
你可以这样做:
canActivate() {
return this.authService.loggedIn().map(res => {
if(!res) {
this.router.navigate(['/login']);
}
return res;
});
}
使用此代码,您遵守签名,并保持您的路由逻辑。