Nim*_*mjo 53 typescript angular-routing angular
我有一个angular2主动防护,如果用户没有登录,它会处理,将其重定向到登录页面:
import { Injectable } from "@angular/core";
import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Observable} from "rxjs";
import {TokenService} from "./token.service";
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor (
private router : Router,
private token : TokenService
) { }
/**
* Check if the user is logged in before calling http
*
* @param route
* @param state
* @returns {boolean}
*/
canActivate (
route : ActivatedRouteSnapshot,
state : RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if(this.token.isLoggedIn()){
return true;
}
this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url }});
return;
}
}
Run Code Online (Sandbox Code Playgroud)
我必须在每条路线上实施它,如:
const routes: Routes = [
{ path : '', component: UsersListComponent, canActivate:[AuthenticationGuard] },
{ path : 'add', component : AddComponent, canActivate:[AuthenticationGuard]},
{ path : ':id', component: UserShowComponent },
{ path : 'delete/:id', component : DeleteComponent, canActivate:[AuthenticationGuard] },
{ path : 'ban/:id', component : BanComponent, canActivate:[AuthenticationGuard] },
{ path : 'edit/:id', component : EditComponent, canActivate:[AuthenticationGuard] }
];
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现canActive选项而不将其添加到每个路径.
我想要的是在主路线上添加它,它应该适用于所有其他路线.我搜索了很多,但我找不到任何有用的解决方案
谢谢
Gün*_*uer 132
您可以引入无组件父路线并在那里应用警卫:
const routes: Routes = [
{path: '', canActivate:[AuthenticationGuard], children: [
{ path : '', component: UsersListComponent },
{ path : 'add', component : AddComponent},
{ path : ':id', component: UserShowComponent },
{ path : 'delete/:id', component : DeleteComponent },
{ path : 'ban/:id', component : BanComponent },
{ path : 'edit/:id', component : EditComponent }
]}
];
Run Code Online (Sandbox Code Playgroud)
您还可以在app.component的ngOnInit函数中订阅路由器的路由更改,并从那里检查身份验证,例如
this.router.events.subscribe(event => {
if (event instanceof NavigationStart && !this.token.isLoggedIn()) {
this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url}});
}
});
Run Code Online (Sandbox Code Playgroud)
当路线改变时,我更喜欢这种方式来进行任何种类的应用范围检查。
| 归档时间: |
|
| 查看次数: |
21133 次 |
| 最近记录: |