【问题标题】:Angular 2 CanActivate is called twiceAngular 2 CanActivate 被调用两次
【发布时间】: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 语句...

标签: angular angular2-routing


【解决方案1】:

虽然这不是一个解决方案,但它是一个答案:

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

这可能是 Angular 路由器中的一个错误。

我还在调查是否有解决方案。

史蒂夫

【讨论】:

  • 现在是 2018 年,我仍然遇到这个问题,这是因为哈希路由。你找到解决办法了吗?
  • 恐怕我没有解决办法。它最终冒险并使用 MVC 风格的路由而不是哈希路由。
【解决方案2】:

请去掉路由链接前的斜线。

redirectTo: "meal-list"

【讨论】:

    【解决方案3】:

    我注意到它不适用于 Hash: 下面是我的例子,请注意:下面的代码将调用 penModalDialogInvalid() 我用了两次

    providers: [{provide:LocationStrategy,useClass:HashLocationStrategy}],
    
    
    
       @Injectable()
    export class UserDetailsGuard implements CanActivate {
    
    
    constructor(private _router:Router,
        private winRef: WindowRef){}
    
     canActivate(route:ActivatedRouteSnapshot,state: RouterStateSnapshot ) : boolean {
    
        let id=+route.url[0].path;
    
        if (isNaN(id) || id <1 ){
            this.winRef.nativeWindow.openModalDialogInvalid();
            //this._router.navigate(['/pagenotfound']);
            return false;
        }
        return true;
    
    } 
    
    }
    

    如果我注释掉上面的导航行,它会调用一次函数!!!!否则两次,除了 Firefox 和所有基于 Firefox 的浏览器!!!!为什么????不知道!!!!!

    【讨论】:

    • 您找到解决此问题的方法了吗?
    • 并非如此。但是如果必须的话,我们可以消除 Hash 策略,但要记住发布 Angular App 时的路由问题。
    【解决方案4】:

    角度库中的一个错误。 在 12.1.2 版本中解决。 (4年后)。 https://github.com/angular/angular/issues/13586#issuecomment-881627456

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 2018-08-18
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2021-04-09
      • 2019-11-16
      • 2017-04-24
      相关资源
      最近更新 更多