针对不同用户的角度路由视图

时间:2017-12-02 18:59:26

标签: angular typescript authentication routing

我正在尝试在我的Angular 4应用中为3种类型的用户设置路由。

用户登录后,他将被重定向到我的app-component。这就是我的 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..

因此,根据用户类型,我想加载完全不同的视图,这在我的项目中的结构是这样的。我想为每个用户提供不同的导航栏,不同的编辑配置文件组件等。实现此目的的正确方法是什么,因为一旦登录,我将收到重定向到app-component的用户类型,因此我将能够发送这是它的孩子 - 牙医视图组件,患者视图组件等。

为了让你更好地了解类似的替代方案,但路由会很棒:(免责声明:我知道这是不可能的: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>

由于我是新手,并且仍然在想办法,我想知道我是朝着正确的方向前进,还是走错了方向。任何建议都很受欢迎。

1 个答案:

答案 0 :(得分: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 { }
相关问题