Angular2防护装置和路由器
我有一个登录系统,当且仅当我们登录时才允许访问模块。如果我们没有,并且会话已过期,那么我会重定向到登录页面,并将我们所在的页面保存在会话存储中,因此如果用户再次尝试登录,他会返回到他所在的页面。 但是,我有一个问题需要警惕:Angular2防护装置和路由器,angular,router,Angular,Router,我有一个登录系统,当且仅当我们登录时才允许访问模块。如果我们没有,并且会话已过期,那么我会重定向到登录页面,并将我们所在的页面保存在会话存储中,因此如果用户再次尝试登录,他会返回到他所在的页面。 但是,我有一个问题需要警惕: @Injectable() export class AuthGuard implements CanActivate { constructor(private _router: Router, private _authUtils: AuthUtils) {}
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private _authUtils: AuthUtils) {}
canActivate(): boolean {
if(this._authUtils.isLogged()) {
return true
}
else {
window.sessionStorage.setItem('previousPage', this._router.url)
let link = ["/login", { previous: "true" }]
this._router.navigate(link)
return false
}
}
}
这个问题源于此。_router.url尚未初始化,因此每次都返回“/”。如果我强制它等于我的一条路径,那么它工作得非常好。你知道我如何解决这个问题吗
干杯
编辑:
以下是我的app-routing.module.ts中的内容:
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'myApp',
loadChildren: 'app/myApp.module#MyAppModule',
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent,
data: {
name: 'login'
}
},
{
path: '**',
redirectTo: '/login',
pathMatch: 'full'
}
]
)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
您可以使用from paramater获取当前URL
例如
因此,我认为您可以将您的AuthGuard
更改为:
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivate
} from '@angular/router';
// other import ....
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private _authUtils: AuthUtils) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this._authUtils.isLogged()) {
return true
}
else {
window.sessionStorage.setItem('previousPage', state.url)
let link = ["/login", { previous: "true" }]
this._router.navigate(link)
return false
}
}
}
您可以使用from paramater获取当前URL
例如
因此,我认为您可以将您的AuthGuard
更改为:
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivate
} from '@angular/router';
// other import ....
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private _authUtils: AuthUtils) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this._authUtils.isLogged()) {
return true
}
else {
window.sessionStorage.setItem('previousPage', state.url)
let link = ["/login", { previous: "true" }]
this._router.navigate(link)
return false
}
}
}
请在您声明AuthGuard的app.module中添加代码。您想在那里看到什么,我的意思是它只出现在我的提供程序中:as:AuthGuard请在您声明AuthGuard的app.module中添加代码。您想在那里看到什么,我的意思是它只出现在我的提供程序中:as:AuthGuard