gpt4 book ai didi

javascript - 使用 canActivate 防护时 redirectTo 不起作用

转载 作者:太空狗 更新时间:2023-10-29 17:40:47 26 4
gpt4 key购买 nike

redirectTo 属性在我的 Angular 2 应用程序中不起作用。我的 app.routing.ts 中有以下路线:

const routes: Routes = [
{ path: '', redirectTo: '/page/1', pathMatch: 'full' },
{ path: 'page', loadChildren: 'app/modules/page/page.module#PageModule' }
]

export const routing = RouterModule.forRoot(routes);

然后,在我的 page.routing.ts 中,我有以下内容:

const pageRoutes: Routes = [
{ path: ':id', component: PageComponent, canActivate: [LoginGuard] }
];

export const pageRouting = RouterModule.forChild(pageRoutes);

每次我访问主页时,它都会显示 LoginComponent 一秒钟,然后消失。但是,它应该重定向到 PageComponent

为什么没有发生?如果用户已经登录,为什么要加载 LoginComponent(即使只是一秒钟)?

这是我的 LoginGuard:

@Injectable()
export class LoginGuard implements CanActivate {

constructor(private af: AngularFire, private router: Router) {}

canActivate(): Observable<boolean> {
return this.af.auth.map(auth => {
if (auth === null) {
this.router.navigate(['/login']);
return false;
} else {
return true;
}
}).first();
}

}

编辑: 我暂时更改了 LoginComponent 以在用户登录时重定向到 PageComponent。不过我仍然想知道,为什么 redirectTo 不起作用。

最佳答案

我不知道为什么会这样,但我相信如果您在加载 PageModule 之前检查 LoginGuard,它就会起作用。

应用程序路由.ts

const routes: Routes = [
{ path: '', redirectTo: '/page/1', pathMatch: 'full' },
{
path: 'page',
// Call the guard before the module is loaded
canLoad: [ LoginGuard ]
loadChildren: 'app/modules/page/page.module#PageModule'
}
]

export const routing = RouterModule.forRoot(routes);

登录 guard

@Injectable()
export class LoginGuard implements CanActivate, CanLoad {

constructor(private af: AngularFire, private router: Router) {}

// Add this method to validade the canLoad
canLoad(route: Route): Observable<boolean> {
return this.canActivate();
}

canActivate(): Observable<boolean> {
return this.af.auth.map(auth => {
if (auth === null) {
this.router.navigate(['/login']);
return false;
} else {
return true;
}
}).first();
}

}

关于javascript - 使用 canActivate 防护时 redirectTo 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com