Angular 2 CanActivate被调用两次 [英] Angular 2 CanActivate is called twice

查看:231
本文介绍了Angular 2 CanActivate被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Angular的路由守卫时遇到问题.

I am faced with a problem with route guards with Angular.

导航到我未登录的不允许页面时,我的CanActivate防护被调用了两次.

My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in.

我有1个根模块,并在那里提供了我的CanActivate防护和其他服务.

I have 1 root module and provided there my CanActivate guard and other services.

提前谢谢!

这是我的路由器:

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;
  }
}

推荐答案

尽管这不是解决方案,但却是一个答案:

Although this is not a solution, it is an answer:

在使用哈希路由(useHash:true)时会发生这种情况.

This happens when using hash routing (useHash: true).

这可能是Angular路由器中的错误.

It may be a bug in the Angular router.

我仍在调查是否有解决方案.

I am still investigating to see if there is a solution.

史蒂夫

这篇关于Angular 2 CanActivate被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆