您可以将 Angular 组件放在不同的模块中。这样做的好处是您可以更好地管理依赖项,并且开发人员不必接触相同的文件。
我在所有项目中使用的文件夹结构:
core/
- login/
- auth/
- core.module.ts // Register the root routes here (RouterModule.forRoot)
- core.route.ts // Your lazy loaded routes for the core modules (login for example)
feature/
- home/
-- home.component.html
-- home.component.scss
-- home.component.ts
-- home.module.ts // Register the component and module route here (RouterModule.forChild)
- feature.module.ts // Register the feature routes here (RouterModule.forChild)
- feature.route.ts // Your lazy loaded routes for the feature modules (Example: The home page)
shared/ // Put any components/pipes/services that are shared over multiple components here
-- shared.module.ts // You can put dependencies that you share across multiple modules here (Example: Angular material imports)
app.module.ts
app.component.ts
这种结构将身份验证、页面和共享功能的逻辑分开。它还捆绑了一个组件/小模块,以便它可以独立开发并且可以轻松更换。
例子
您可以在这个 stackblitz中找到一个关于它如何适合实际应用程序的示例。
回答您的问题
@Injectable({providedIn: root})
从 Angular 6 开始,您可以使用语法注册您的服务。这意味着您的服务将是全局可用的(您不必在providers
使用它之前将它添加到数组中)并且如果它没有被注入到任何地方。
组件应始终在declarations
数组中注册。但是您可以在声明组件的地方创建小模块。
通过RouterModule.forChild()
您可以创建组件特定的路由。将此与延迟加载相结合,您可以更好地了解您的功能并获得更好的整体性能。
延迟加载
您可以使用延迟加载的路由来提高应用程序的速度和解耦。这是因为惰性路由(loadChildren
在routes
数组中)只指向一个路径。这样,您可以用其他模块(具有相同名称)替换该模块,而无需更改引用(我们需要更改的文件更少!:D)。
导入示例:
{
path: HOME_MODULE_ROUTE,
loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
// Add auth guard here to only show the page when the user is logged in
},
要进一步提高应用程序的性能,您可以使用PreloadingStrategy。我建议使用PreloadAllModules策略,以便在不打扰用户的情况下加载您的模块,并加快应用程序的进一步加载和导航(更多此处)。
在字符串上使用常量
为了避免在删除路由时出现大量调试和/或运行时问题,我建议使用常量。这样,您就有 1 个地方可以定义页面路由,并且可以避免字符串比较。请注意,您需要一个单独的文件。您不能在路由文件中添加路由,因为这会产生循环依赖。