2017-08-27 28 views
0

路由組件我已經定義了一個解析器我的註冊路線:重定向,而無需加載在角2/4

import {IsLoggedin} from './share/is-loggedin.service'; 

const appRoutes: Routes = [ 
    {path: 'signup', resolve: [IsLoggedin], component: SignupComponent} 
] 

在我重定向到某個頁面如果用戶登錄的分解:

resolve(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) { 
    this.authService.isUserAuthenticated() 
       .subscribe(
        (res: any) => { 
         if (res === true) { 
          this.router.navigate(['/main-board']); 
         } 
        } 
       ); 
} 

但是,角負載SignupComponent反正重定向到主板頁面之前。

注:我試着CanActivate後衛,但它仍然離不開加載作爲組元方法isUserAuthenticated()返回一個Observable並不起作用同步的方式重定向。

我真的很想知道是否有可能在不加載SignupComponent的情況下重定向到主板頁面。

它可以在角度2/4中順利完成嗎?

我真的很感激,如果有人幫助我。

+4

考慮使用守衛你的情況。也許是一名CanActivate後衛? https://angular.io/api/router/CanActivate – eroak

+0

'CanActivate'仍然無法重定向,因爲isUserAuthenticated()方法返回一個Observable並且不工作同步方式 – asmmahmud

回答

0

如果使用CanActivate代替Resolve,那麼重定向將是平滑的。然後,它會不會重定向之前加載路由組件SignupComponent

import {IsLoggedin} from './share/is-loggedin.service'; 

const appRoutes: Routes = [ 
    {path: 'signup', canActivate: [IsLoggedin], component: SignupComponent} 
] 

的在IS-loggedin.service.ts:

canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot) { 
    /* this.authService.isUserAuthenticated() return an http Observable */ 
    return this.authService.isUserAuthenticated() 
       .map((res: any) => { 
         if (res === true) { 
          this.router.navigate(['/main-board']); 
          return false; 
         } 
         return true; 
        } 
       ); 
} 
相關問題