重定向使用canActivate guard

时间:2016-10-30 23:52:17

标签: javascript angular angular-routing angular-services

我的Angular 2应用中的redirectTo属性不起作用。我的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不工作。

1 个答案:

答案 0 :(得分:0)

我不确切知道为什么会发生这种情况,但我相信如果您在PageModule加载之前检查了LoginGuard,它就能正常工作。

app.routing.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);

LoginGuard

@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();
  }

}