基于角色的相同路径上的延迟加载模块 [英] Lazy load modules on same path based on role
问题描述
我正在尝试根据自己的角色加载Angular模块(登录时).我用Angular Guard尝试了一下,但是没有用,当它失败时,它就不会进入下一条路线.
I am trying to load an Angular Module based on my role (when I am logged in). I tried it with an Angular Guard but that is not working, when it fails it does not go to the next route.
const routes: Routes = [
{
path: '',
loadChildren: () => AuthModule
// Load when not logged in
},
{
path: '',
loadChildren: () => AdminModule
// Load when admin
},
{
path: '',
loadChildren: () => CrewModule
// Load when crew
}
];
有关如何解决此问题的任何想法?我认为Angular Guard或使用匹配器不是解决此问题的正确方法...
Any ideas for how to fix this? I think an Angular Guard or using a matcher is not the right solution for this...
对于每个路径/模块,我都有自己的防护对象,如下所示:
For each path/module I have my own guard looking like the following:
import { Injectable } from '@angular/core';
import { CanLoad, CanActivate, Route, Router } from '@angular/router';
import { AuthService } from '@app/core';
@Injectable()
export class AdminModuleGuard implements CanLoad {
constructor(private authService: AuthService, private router: Router) {}
canLoad(route: Route): boolean {
const url: string = route.path;
console.log('Admin Module Load Guard - Url:' + url);
return false;
}
}
谢谢!
贵族,雅尼克
推荐答案
您可以通过使用根模块的 Injector
访问您的 AuthService
实例来完成此操作,基于用户角色加载一个模块或另一个模块的异步决策.您可以在 main.ts
文件中进行引导后立即访问 Injector
,然后将其发布为RxJs主题(例如mySubject $),然后在您的路线中使用该主题定义.
You can accomplish this by using your root module's Injector
to access your AuthService
instance, and then make an asynchronous decision to load one module or the other based on user's role. You can access the Injector
immediately after the bootstrapping in your main.ts
file, and then publish as an RxJs subject (say mySubject$) and then use this subject in your route definition.
// Get root module's injector and publish it via RxJs subject
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then((m) => mySubject$.next(m.injector)) // <-- here
.catch((err) => console.error(err));
这篇关于基于角色的相同路径上的延迟加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!