首页 文章

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

提问于
浏览
0

我正在尝试在我的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

    这个回答是基于@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 { }
    

相关问题