gpt4 book ai didi

javascript - 延迟加载模块可以使用 root 注入(inject)的 canActivate 防护吗?

转载 作者:行者123 更新时间:2023-12-03 00:27:44 24 4
gpt4 key购买 nike

我有一个stackblitz books module具有以下路径:

export const routes: Routes = [
{ path: 'find', component: FindBookPageComponent },
{ path: ':id', component: ViewBookPageComponent },
{ path: '', component: CollectionPageComponent },
];

在同一个应用程序中,services 文件夹中还有一个根注入(inject)的 AuthGuard 服务。如果将该防护添加到 books 模块中的任何路由,应用程序将永远旋转并且不会启动。

是否可以在模块中使用根注入(inject)的 CanActivate 防护,而不在模块的 providers 数组中指定它?

The documentation I have looked at show the guards being registered with the AppComponent providers ,所以我认为 root 注入(inject)守卫就可以了?

如果一定要指定的话,还可以root注入(inject)吗?

AuthGuard 依赖于 StateService,如果它不能被 root 注入(inject),那么我假设的 StateService 也不能?

最佳答案

Can a root injected CanActivate guard be used in a module without specifying it in the providers array of the module?

从技术上讲,它已经被指定。 @Injectable({provideIn: 'root'}) 告诉 Angular 编译器将其添加到主模块的提供程序列表中。它只是添加到 Angular 中的一个便利功能。

根模块是由入口 TypeScript 文件中的 platformBrowserDynamic().bootstrapModule(module) 定义的模块(通常命名为 main.ts)。

If that guard is added to any of the routes in the books module, the application spins forever and will not launch.

听起来AuthGaurd返回了一个未完成的可观察对象。尝试将 return observable.pipe(first()); 添加到防护函数。

所有使用可观察量的路由器功能(canActive、canLoad、resolve 等)都要求可观察量完整。

The documentation I have looked at show the guards being registered with the AppComponent providers, so I assumed that it would be ok to root inject the guards?

在这种情况下,该模块与声明根路由的模块相同。您可以看到 RouterModule.forRoot(appRoutes) 用于导入具有顶级路由的路由器。因此,路由器可以看到此级别提供程序中定义的任何内容,因为它们共享相同的注入(inject)器。

The AuthGuard depends on a StateService and if it cannot be root injected, then neither can the StateService I assume?

如果在注入(inject)器尝试实例化类时尚未声明提供程序,则会出现运行时错误,指出构造函数具有未知的可注入(inject)项。这是一条类似于 error: constructor(?) 的消息,其中问号是未知参数。

这意味着如果稍后将 StateService 定义为提供程序,则 AuthGaurd 将无法启动。这取决于 AuthGaurd 首次使用的时间,因为它们只有在首次使用时才会创建。

关于javascript - 延迟加载模块可以使用 root 注入(inject)的 canActivate 防护吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com