2017-12-02 200 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 { }