我正在使用角度2.4版本和路由器版本“^ 3.4.10”。angular2:如何获得CanLoad守卫的完整路径,同时保持重定向url
我正在尝试使用身份验证警卫服务来处理重定向url。
当用户点击url'domain/assignment/3/detail'时,如果用户没有登录,则用户重定向到'domain/login'页面。 ,并且当用户成功登录到系统时,然后重定向到用户尝试访问的'domain/assignment/3/detail'前一个URL。
我在分配模块上实现了CanLoad guard。因此当用户尝试访问url'domain/assignment/3/detail'时,如果用户未登录,则url存储到authservice(this.authService.redirectUrl)的redirectUrl属性中。
所以这里是问题出现在我的情况。我无法获得用户点击的网址的完整路径。 我在CanLoad后卫中获得'赋值'而不是'赋值/ 3 /细节'。 我如何获得完整路径,以便我可以将用户重定向到CanLoad守卫中的正确路径。
CanLoad:
canLoad(route: Route): boolean {
let url = `/${route.path}`; // here i got url path 'assignment' instead 'assignment/3/detail'
return this.checkLogin(url);
}
主路由 app.routes.ts
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent},
{
path: 'assignment',
loadChildren: './assignment/assignment.module#AssignmentModule',
canLoad: [AuthGuard]
},
{ path: '**', redirectTo: '', pathMatch: 'full' }];
分配路由:赋值routing.ts
const assignmentRoutes: Routes = [
{
path: '',
component: AssignmentComponent,
canActivate: [AuthGuard]
children: [
{
path: '',
canActivateChild: [AuthGuard],
children: [
{
path: ':assignmentId/detail', component: AssignmentDetailComponent,
canActivate: [AuthGuard]
}
]
}]
}];
AuthGuard:auth-gurad.service.ts
import { Injectable } from '@angular/core';
import {
CanActivate, Router,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanActivateChild,
NavigationExtras,
CanLoad, Route
} from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
canLoad(route: Route): boolean {
let url = `/${route.path}`; // here i got url path 'assignment' instead 'assignment/3/detail'
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) {
if(this.authService.redirectUrl!=null){
let redirectUrl = this.authService.redirectUrl;
this.authService.redirectUrl = null;
this.this.router.navigate([redirectUrl]);
}
return true;
}
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page
this.router.navigate(['/login']);
return false;
}
}
谢谢埃德温的建议和答案。 – Krishna