【发布时间】:2017-03-13 21:18:01
【问题描述】:
我遇到了 Angular 的路由保护问题。
导航到由于我未登录而不允许访问的页面时,我的 CanActivate 守卫被调用了两次。
我有 1 个根模块,并在那里提供了我的 CanActivate 保护和其他服务。
提前谢谢你!
这是我的路由器:
const appRoutes: Routes = [
{
path: "",
pathMatch: "full",
redirectTo: "/meal-list",
},
{
path: "login",
component: LoginComponent,
},
{
path: "meal-list",
component: MealListComponent,
canActivate: [AuthActivateGuard],
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
和守卫:
@Injectable()
export class AuthActivateGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
console.log("guard created");
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
if (!this.authService.authenticated) {
return this.authService.checkLogged().map(res => {
this.authService.authenticated = true;
return true;
}).catch(()=> {
this.authService.authenticated = false;
this.router.navigate(["login"]);
return Observable.of(false);
});
}
return true;
}
}
【问题讨论】:
-
随便看看,您的代码中似乎有很多
return语句...