redirectTo使用canActivate后卫时无法正常工作

bri*_*s69 5 javascript angular-routing angular-services angular

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);
Run Code Online (Sandbox Code Playgroud)

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

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

export const pageRouting = RouterModule.forChild(pageRoutes);
Run Code Online (Sandbox Code Playgroud)

每次我访问主页时它会显示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();
  }

}
Run Code Online (Sandbox Code Playgroud)

编辑:暂时,我改变了LoginComponent重定向到PageComponent如果用户登录.但我仍然想知道,为什么redirectTo不工作.

fel*_*ima 1

我不知道为什么会发生这种情况,但我相信如果您在 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);
Run Code Online (Sandbox Code Playgroud)

登录卫士

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

}
Run Code Online (Sandbox Code Playgroud)