0

我想基于同一(“”)路径(主页)上的用户角色加载特定的 Angular 模块。假设我有两个模块,名为 AdminModule 和 OperatorModule。如果角色是 ADMIN,那么我想加载 AdminModule,否则加载 OperatorModule。我想用 Angular Guard 存档。

现在app.routing.ts我添加了以下代码:

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

import { AuthGuard } from './core/guards/auth.guard';

import { AdminModule } from './modules/admin';
import { OperatorModule } from './modules/operator';

const routes: Routes = [
   {
      path: '',
      loadChildren: () => AdminModule,
      canLoad: [ AuthGuard ],
      data: { role: 'ADMIN' }
   },

   {
      path: '',
      loadChildren: () => OperatorModule,
      canLoad: [ AuthGuard ],
      data: { role: 'OPERATOR' }
   },
];

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

我已经使用以下代码实现了 AngularGuard,它必须显示 OperatorModule:

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

@Injectable({
   providedIn: 'root'
})
export class AuthGuard implements CanLoad {
   constructor(private router: Router) {}

   canLoad(route: Route): Promise<boolean> | boolean {
      if (route.data.role === 'OPERATOR') {
         return true;
      }

      return false;
   }
}

在第一条路线失败后它以某种方式停止寻找,我做错了什么吗?

djerid 的 StackBlitz 示例:https ://stackblitz.com/edit/angular-vd4oyu?file=app%2Fapp-routing.module.ts

===

Matcher 也不起作用:

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

import { AuthGuard } from './core/guards/auth.guard';

import { AdminModule } from './modules/admin';
import { OperatorModule } from './modules/operator';

const routes: Routes = [
   {
      loadChildren: () => AdminModule,
      matcher: AdminMatcher,
      data: { role: 'NO' }
   },

   {
      loadChildren: () => OperatorModule,
      matcher: OperatorMatcher,
      data: { role: 'OPERATOR' }
   },
];

@NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule]
})
export class AppRoutingModule {
   constructor() {

   }
}


import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';
export function AdminMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route) {
   const isPathMatch = segments[0].path === route.path;

   if (isPathMatch && route.data.role === 'ADMIN') {
      return { consumed: [segments[0]] };
   } else {
      return null;
   }
}

export function OperatorMatcher(segments: UrlSegment[], group: UrlSegmentGroup, route: Route) {
   const isPathMatch = segments[0].path === route.path;

   if (isPathMatch && route.data.role === 'OPERATOR') {
      return { consumed: [segments[0]] };
   } else {
      return null;
   }
}
4

2 回答 2

0

最好的方法是使用UrlMatchers而不是 canLoad ,根据您的条件匹配每一个,当 2 个路径之一匹配时,另一个将被自动忽略

 const routes: Routes = [{
  path: '',
  matcher: adminMatcher,
  oadChildren: () => AdminModule,
  data: { role: 'ADMIN' }
 },
 {
  path: '',
  matcher: operatormatcher,
  loadChildren: () => OperatorModule,
  data: { role: 'OPERATOR' }

 }]

检查这个例子

于 2019-04-12T14:01:00.950 回答
0

这是一个老问题,但我在这里留下一个答案,以防有人偶然发现这个问题。injector我通过在我的延迟加载路由中使用根模块解决了这个问题。

您可以查看stackblitz上的工作解决方案。

解决方案

步骤1

创建一个导出ReplaySubject<Injector>.

import { Injector } from '@angular/core';
import { ReplaySubject } from 'rxjs';

// Feel free to optimize this implementation if you want to
// expose `Observable<Injector>` instead of the subject itself.
export const appInjector = new ReplaySubject<Injector>();

第2步

main.ts中,获取根模块的句柄Injector并将其发布到appInjector您在上面创建的主题:

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .then((m) => appInjector.next(m.injector)) // publish root module's injector
  .catch((err) => console.error(err));

第 3 步

这是我们根据某些异步条件修改需要异步延迟加载不同模块的路由的步骤。

const routes: Routes = [
  // other routes
  // ...
  // ...
  // conditional route
  {
    path: "dashboard",
    component: LayoutComponent,
    canActivate: [DashboardAuthGuard], // block this route if user is not logged-in
    loadChildren: () =>
    
      // Use the appInjector subject
      appInjector.pipe(
        
        // ...to get a handle to your AuthService
        map((injector) => injector.get(AuthService)),
        
        // ...then switch to a new observable
        switchMap((authService) => {
          
          // ...that uses authService to retrieve the logged-in user
          return authService.user$.pipe(
            
            // ...then switches again, this time to actually lazy-load a feature module
            switchMap((user) => {
              
              // ...but first let's check the user's role
              switch (user.role) {
                
                // ...and load Admin Feature Module if user.role is 'admin'
                case "admin":
                  return import(
                    "./modules/admin-dashboard/admin-dashboard.module"
                  ).then((m) => m.AdminDashboardModule);
                
                // ...or load User Feature Module if user.role is 'user'
                case "user":
                  return import(
                    "./modules/user-dashboard/user-dashboard.module"
                  ).then((m) => m.UserDashboardModule);
              }
            })
          );
        })
      ),
  },
];
于 2020-12-03T18:17:32.103 回答