2017-12-02 202 views
0

我正在嘗試爲3種類型的用戶在我的角度4應用中設置路由。針對不同用戶的角度路由視圖

一旦用戶登錄,他將被重定向到我的應用程序組件。這就是我的APP-component.html樣子:

<div class="main-container"> 
    <div class="wrapper"> 
    <router-outlet></router-outlet> 
    </div> 
</div> 

我要檢查一下用戶的類型,並根據這 - 在我的路由器出口打開了不同的路線。爲了給你一個想法,我會告訴你,我要爲結構:

index.html 
>app-component 
>register-component 
>login-component 
>dentist-view 
    schedule component 
    patients component 
    profile component 
    appointments component etc.. 
>admin-view 
    manage users component 
>patient-view 
    ambulatory-lists component 
    profile component 
    dentist search component 
    book appointment component etc.. 

所以根據我想加載完全不同的看法,用戶類型,在我的項目,這樣的結構等。我想爲每個用戶使用不同的導航欄,不同的編輯配置文件組件等等。什麼是正確的方法來實現這一點,因爲一旦登錄,我將收到重定向到應用程序組件的用戶類型,所以我將能夠發送它對它的孩子 - 牙醫檢查組件,患者查看組件等。

爲了給你一個更好的主意,就像這個替代方案,但路由將是偉大的:(聲明:我知道這個是不可能的:d) 在app.component.html

<div class="main-container"> 
    <div class="wrapper"> 
    <router-outlet> 
    <dentist-component *ngIf="isDentist()"></dentist-component> 
    <patient-component *ngIf="isPatient()"></patient-component> 
    <admin-component *ngIf="isAdmin()"></admin-component> 
    </router-outlet> 
    </div> 
</div> 

由於我是新來這一點,仍然盤算的事情了,我想知道如果我爲首的權方向或完全錯誤的方式。任何建議,非常感謝。

回答

0

這個答案是基於@abdul hammed answer 更多信息在Angular.io documentation

衛隊是解決方案(guard.service):

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

    @Injectable() 
    export class Guard implements CanActivate { 
     canActivate() { 

    if (this.user && this.user.profile.role == 'Dentist') { 
      this.router.navigate(['dentist']); 
     } if else (this.user && this.user.profile.role == 'Patient') { 
      this.router.navigate(['patient']); 
     } ... 

     return true; 
     } 

constructor(private router: Router) { } 
    } 

而且你必須更新你的app.module文件,

import { Guard } from './_services/guard.service'; 
import { DentistComponent } from './dentist/dentist.component'; 
import { PatientComponent } from './dentist/patient.component'; 
@NgModule({ 
    declarations: [ 
    AppComponent, 
    DentistComponent, 
    PatientComponent 
    ], 
    imports: [ 
    BrowserModule, 
    HttpModule, 

    RouterModule.forRoot([ 
     { 
      path: 'dentist', 
      component: DestistComponent, 
      canActivate:[Guard] 
     }, 
     { 
     path: 'patient', 
     component: PatientComponent, 
     canActivate:[Guard] 
     } 
    ]) 
    ], 
    providers: [Guard], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { }