[英]Understanding canactivate and routes in angular 2
I am trying to check if a user is authorized and if not direct him/her to login page. 我正在尝试检查用户是否被授权,以及是否未将其引导到登录页面。 I actually managed to do that but i am having an hard time how the mechanism works.
实际上,我确实做到了这一点,但是我对该机制的工作方式感到困难。 please see below code.
请参见下面的代码。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let fus: FakeUserService = new FakeUserService();
if(!fus.authorization()){
this.router.navigate(['login']);
return false; // Code works even this line is commented out. The user is redirected to the login page.
}
return true;
}
The point i don`t understand is how router.navigate works in this scenario. 我不明白的是在这种情况下router.navigate的工作方式。 Does user go to the intended page and navigated back to login when i comment out "return false"?.
当我注释掉“ return false”时,用户是否转到预期的页面并导航回登录? Or "router.navigate" function overrides all the routing commands?
还是“ router.navigate”功能会覆盖所有路由命令? I am kind of confused..
我有点困惑。
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";
@Injectable()
export class AuthGuard implements CanActivate{
constructor(protected router: Router)
{
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot):Observable<boolean> | boolean{
console.log("In Can Activate AuthGuard");
if(route.params['key'] == "X"){
return true;
}
this.router.navigate(['/home',{message:"Not Authorised"}]);
return false;
}
}
Route 路线
{ path: 'guardcheck', component: CheckComponent , canActivate: [AuthGuard]},
In the above example we return true when we want the user to proceed with the route on which the guard is placed and if not we navigate to the error page using router navigate and return false .
在上面的示例中,当我们希望用户继续使用放置防护装置的路线时,我们返回true;否则,我们使用router navigation导航到错误页面并返回false。
This false returned is for the guard to know that the condition failed . 返回的此错误是为了让警卫知道条件失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.