我正在尝试加载我的应用程序的主页,供未经身份验证的访问者使用。
const routes: Routes = [
{ path: '', loadChildren: './home/home.module#HomeModule' }
...经过身份验证的用户应该通过该模块(也是在空路径上)获取他们的提要。
{ path: '', loadChildren: './feed/feed.module#FeedModule', canActivate: [IsAuthenticationGuard] },
{ path: '', loadChildren: './home/home.module#HomeModule', canActivate: [NoAuthenticationGuard] },我希望IsAuthenticationGuard会失败并加载默认的主组件。
相反,它确实下载了提要模块包(如“网络”选项卡所示),但在路由器出口中没有加载任何内容。非常令人困惑。
如何在空路径上执行条件路由(基于保护或其他)?
更新:这是按要求提供的警卫
@Injectable()
export class IsAuthenticationGuard implements CanActivate {
constructor(
private authenticationService: AuthenticationService
) { }
public canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.authenticationService.isAuthenticated.pipe(take(1), map((isAuthentication) => {
return isAuthentication;
}));
}
}我已经研究了新的urlTree,很酷的是,您现在可以通过路线重定向,而不是在警卫内部。然而,如果您尝试使用不同模块的相同路由,则重定向似乎不适用。如果有方法, Plz会纠正我。
发布于 2020-06-29 14:38:14
事实证明,这在常春藤之前基本上是不可能的。现在,在角度9/10,我们可以懒惰加载功能模块,没有路由器非常容易。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
private compiler: Compiler,
private injector: Injector
){ }
public ngOnInit(): void {
if (loggedin) {
this.loadModule(await import('./lazy/lazy.module').then(m => m.LazyModule));
} else {
this.loadModule(await import('./lazy2/lazy2.module').then(m => m.Lazy2Module));
}
}
async loadModule(module: Type<any>) {
let ref;
try {
this.container.clear();
// Angular < 13
const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef: any = moduleFactory.create(this.injector);
const componentFactory = moduleRef.instance.resolveComponent(); // ASSERTION ERROR
ref = this.container.createComponent(componentFactory, null, moduleRef.injector);
// Angular 13 update
const moduleRef = createNgModuleRef(module, this.injector);
const componentFactory = moduleRef.instance.resolveComponent();
ref = container.createComponent(
componentFactory,
undefined,
moduleRef.injector
);
} catch (e) {
console.error(e);
}
return ref;
}
}https://stackoverflow.com/questions/53937128
复制相似问题