相关疑难解决方法(0)

有条件地在Angular路由器的空路径上加载模块

我正在尝试为未经过身份验证的访问者加载我的应用的主页.

const routes: Routes = [
    { path: '', loadChildren: './home/home.module#HomeModule' }
...
Run Code Online (Sandbox Code Playgroud)

经过身份验证的用户应该通过该模块获取其Feed,也是在空路径上.

{ path: '', loadChildren: './feed/feed.module#FeedModule', canActivate: [IsAuthenticationGuard] },
{ path: '', loadChildren: './home/home.module#HomeModule', canActivate: [NoAuthenticationGuard] },
Run Code Online (Sandbox Code Playgroud)

我希望这IsAuthenticationGuard会失败并加载默认的主组件.

相反,它会下载Feed模块包(显示在网络选项卡中),但在路由器插座中没有任何内容.很混乱.

如何在空路径上进行条件路由(基于防护或其他方式)?

更新:这是按要求提供的警卫

@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;
        }));
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经研究了新的urlTree,它很酷,你现在可以通过路线而不是在守卫内重定向.但是,如果您尝试使用具有不同模块的相同路由,则重定向似乎不适用.如果有办法,Plz纠正我.

javascript routing module angular

7
推荐指数
1
解决办法
748
查看次数

如何获取 Angular v13 中动态加载的组件的模块?

在 v12 中,您可以使用以下代码动态加载/导入组件,通过访问它NgModuleComponentFactory然后使用ViewContainerRef.

const injector: Injector = /* injected */
const cfg: ComponentFactoryResolver = /* injected */
const module = await import('path/to/component/file');
const componentDef = module['MyComponent'];
const cf: ComponentFactory = cfg.resolveComponentFactory(componentDef);
const compModule: NgModuleRef = (cf as any).ngModule;

const container: ViewContainerRef = /*retrieved using @ViewChild*/
container.createComponent(cf, null, injector, compModule)
Run Code Online (Sandbox Code Playgroud)

从 v13 开始,ComponentFactory( docs ) 和ComponentFactoryResolver( docs ) 现在被标记为已弃用,并且添加了一个新签名ViewContainerRef.createComponent,该签名接受 acomponentType: Type<C>作为第一个参数。

abstract createComponent<C>(componentType: Type<C>, options?: { …
Run Code Online (Sandbox Code Playgroud)

angular angular13

5
推荐指数
2
解决办法
6025
查看次数

标签 统计

angular ×2

angular13 ×1

javascript ×1

module ×1

routing ×1