2017-05-22 28 views
3

登錄我有這樣的路線:角2重定向用戶是否在

const routes: Routes = [ 
    { path: '', redirectTo: '/login', pathMatch: 'full' }, 
    { path: 'login', component: LoginComponent }, 
    { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, 
]; 

AuthGuard

export class AuthGuard implements CanActivate, CanActivateChild { 
    constructor(private router: Router, 
       private authService: AuthService) { } 

    canActivate() { 
    if (this.authService.isLoggedIn()) { 
     return true; 
    } 
    this.router.navigate(['login']); 
    return false; 
    } 
} 

當用戶訪問該網站時,他被重定向到登錄頁面。當用戶嘗試訪問/dashboard路由而沒有驗證時也會發生同樣的情況。如果他已登錄,如何將用戶重定向到/dashboard?例如,當我訪問myapp.com並且我已登錄時,我想將其重定向到myapp.com/dashboard

+0

上'canActivate'將無法正常工作這樣做呢? 'if(this.authService.isLoggedIn()){this.router.navigate(['dashboard']);返回true; }'。 – developer033

+0

@ developer033,我試過了,它不起作用!會有一個無限循環。 –

+0

嗯,所以你只能在你的'LoginComponent'(在'ngOnInit')上檢查它.. – developer033

回答

2

在這種情況下,我將一切可能重定向到DashboardComponent使用

{path: '', redirectTo: 'dashboard', pathMatch: 'full'}

和比儀表板部件,如果用戶登錄或不能夠確定的(因爲它具有AuthGuard活性),並且如果用戶沒有登錄它會重定向他登錄。

+0

謝謝,我認爲它會是對的! –

+0

儘管這樣做有效,但它會倒退,只要有人點擊您的主頁,就會迫使您進入「信息中心」流程。使用'resovle'的另一個答案更加靈活,並且避免了重定向到全部位置('/'進入'/ login'或'/ dashboard'而不是'/ - >/dashboard - >/login' –

+0

容易和非常聰明:) thx – Whisher

6

您想查看Route界面中的resolve屬性。 https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html

以下屬性的所有可用於路線:

export interface Route { 
    path?: string; 
    pathMatch?: string; 
    matcher?: UrlMatcher; 
    component?: Type<any>; 
    redirectTo?: string; 
    outlet?: string; 
    canActivate?: any[]; 
    canActivateChild?: any[]; 
    canDeactivate?: any[]; 
    canLoad?: any[]; 
    data?: Data; 
    resolve?: ResolveData; 
    children?: Routes; 
    loadChildren?: LoadChildren; 
    runGuardsAndResolvers?: RunGuardsAndResolvers; 
    _loadedConfig?: LoadedRouterConfig; 
} 

resolve設計,讓您之前程序的路徑加載某些類型的數據。對於resolve簽名看起來是這樣的:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<T>|Promise<T>|T 

我們可以但是忽略了簽名,只是覆蓋它,因爲在這種情況下,我們只是想重定向到/儀表板如果用戶-logged IN-。否則顯示/登錄路由正常。

解決方法是創建一個injectable類並將其附加到登錄路由的resolve屬性。

@Injectable() 
class IsLoggedIn { 
    constructor(
    private router: Router, 
    private authService: AuthService) { 
    } 

    resolve(): void { 
    if (this.authService.isAuthenticated) this.router.navigate(['/dashboard']) 
    } 
} 

在您/登錄路線添加resolve屬性。

{ 
    path: 'login', 
    component: LoginComponent, 
    resolve: [IsLoggedIn] 
} 

現在,只要-logged在 - 用戶試圖去/登錄,他們會被重定向到/儀表板沒有看到登錄頁面。

+1

這個方法重定向確定,但仍然加載模塊! – BenRacicot

0

可能最快的事情是調整您的LoginComponent

鑑於this.authService.isLoggedIn()返回一個布爾值。在你LoginComponent您可以快速檢查狀態ngOnInit如下:

import { Component, OnInit } from '@angular/core'; 
import { Router, ActivatedRoute } from '@angular/router'; 

import {AuthService} from '<path_to_your_auth_service>'; 

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.scss'], 
    providers: [] 
}) 
export class LoginComponent implements OnInit { 
    constructor(
    private _route: ActivatedRoute, 
    private _router: Router, 
    private _authService: AuthService 
) 

    ngOnInit() { 
    // get return url from route parameters or default to '/' 
    this.returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/'; 

    // CHECK THE isLoggedIn STATE HERE 
    if (this._authService.isLoggedIn()) { 
     this._router.navigate([this.returnUrl]); 
    } 

    } 

    // Rest fo the logic here like login etc 

    login() { } 

} 

請注意,您只需要添加這ngOnInit

if (this._authService.isLoggedIn()) { 
    this._router.navigate([this.returnUrl]); 
}