2017-10-05 93 views
0

我有兩個組件SignInComponent和HomeComponent。我希望HomeComponent是我的web應用程序的默認視圖,但用戶必須首先通過SignInComponent登錄,並且這些組件具有與同一Url路由。問題是我不知道如何在它們之間導航,因爲它們具有相同的Url。這裏是我的應用程序,routing.module.ts文件:如何路由到具有相同url的組件

import { NgModule } from '@angular/core'; 
import { RouterModule, Routes } from '@angular/router'; 

import { SignInComponent } from '../components/sign-in/sign-in.component'; 
import { HomeComponent } from '../components/home/home.component'; 

const appRoutes: Routes = [ 
    { path: '', component: HomeComponent, canActivate: [AuthGuard]}, 
    { path: '', component: SignInComponent} 
]; 

@NgModule({ 
    imports: [ 
     RouterModule.forRoot(
      appRoutes, 
      { enableTracing: false } 
     ) 
    ], 
    exports: [ 
     RouterModule 
    ] 
}) 
export class AppRoutingModule {} 

這裏是AuthGuard來檢查線路接入HomeComponent,它將導航用戶SignInComponent,如果他們還沒有登錄:

import { Injectable } from '@angular/core'; 
import { Router, CanActivate } from '@angular/router'; 

import { AuthenticationService } from '../services/authentication.service'; 

@Injectable() 
export class AuthGuard implements CanActivate { 

    constructor(private router: Router, private authService: AuthenticationService) { } 

    canActivate() { 
     if (this.authService.checkCredentials()) { 
      return true; 
     } 
     this.router.navigate(['']); // The problem is here 
     return false; 
    } 
} 
+1

這是一個很難的要求,他們必須是相同的網址?看起來你可能會讓自己變得不必要的困難。 – axlj

+1

我同意axlj。這種情況違背了路線的整個觀點。如果他們必須在同一條路徑上,我會把你的'SignInComponent'放入你的'HomeComponent'中,並放入你的'HomeComponent' ts文件中注入你的'authService',並在你的'ngOnInit()'中放入一些邏輯, 'HomeComponenet'內容或您的'SignInComponent' –

+2

我同意axlj。每個組件應該有一個目的。因此,請考慮爲您的主頁定義一個組件,併爲您的登錄定義一個單獨的組件。 – DeborahK

回答

0

最簡單的方法是爲您的登錄創建路線。

const routes : Routes = [ 
    { 
     path: '', 
     loadChildren: 'app/pages/pages.module#HomeModule' 
    }, { 
     path: 'login', 
     component: LoginComponent 
    },{ 
     path: '404', 
     component: Page404Component 
    }, { 
     path: '**', 
     redirectTo: '/404' 
    } 
]; 

,並在您的家庭routing.module:

const routes: Routes = [ 
    { 
     path: '', 
     canActivate: [AuthGuard], 
     component: HomeComponent, 
     children: [...] 
    } 
] 

並配有後衛,你會重定向到登錄,如果用戶沒有連接。

因此,如果用戶沒有連接,用戶將不會加載所有應用程序。

相關問題