【问题标题】:how to load angular modules based on condition如何根据条件加载角度模块
【发布时间】:2020-10-20 01:28:24
【问题描述】:

我的应用程序主页中有三个模块,moduleA 和 moduleB 在我的应用程序组件中,我正在调用一个名为 session 的 API,并获得一个名为 mode 的响应值。如果模式是模块A,那么我必须从主模块延迟加载模块A模块,如果模式是模块B,那么模块B模块是从主模块加载的。 home 模块是从 app 模块加载的。

任何人都可以建议如何实现这一点。

【问题讨论】:

    标签: angular angular-ui-router lazy-loading angular-components angular9


    【解决方案1】:

    假设你的路由数组是这样构建的:

    const routes: Routes = [
      {
        path: 'app', component: AppComponent
      },
      {
        path: 'home', loadChildren: () => import('../features/home/home.module').then(x => x.Home)
      },
      {
        path: 'moduleA', loadChildren: () => import('../features/moduleA/moduleA.module').then(x => x.ModuleA)
      },
      {
        path: 'moduleB', loadChildren: () => import('../features/moduleB/moduleB.module').then(x => x.ModuleB)
      },
      {
        path: 'moduleC', loadChildren: () => import('../features/moduleC/moduleC.module').then(x => x.ModuleC)
      }
    ];
    

    还有你的 Mode 枚举:

    enum Mode {
      ModuleA = "moduleA",
      ModuleB = "moduleB",
      ModuleC = "moduleC"
    }
    

    只需让 API 调用您的服务器,然后根据响应进行导航:

      constructor(private http: HttpClient,private router: Router) { }
    
     public navigate(internalRoute: string): void {
       this.http.get<Mode>('/loadModule').subscribe(x => {
           switch (x)
           {
             case Mode.ModuleA: this.router.navigateByUrl(`/${x}/${internalRoute}`); break
             case Mode.ModuleB: this.router.navigateByUrl(`/${x}/${internalRoute}`); break
             case Mode.ModuleC: this.router.navigateByUrl(`/${x}/${internalRoute}`); break
           }
         })
     }
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2018-05-22
      • 1970-01-01
      相关资源
      最近更新 更多