javascript - Angular 模块应该是一个空的 JavaScript 模块吗?
问题描述
我现在正在学习Angular 7。我目前很清楚 Angular 中的引导设计以及标记 Angular 组件和模块的元数据对象使用。但是,我仍然没有看到 Angular 模块不是空类的示例或案例。
所以,我目前想知道:
- Angular Module 只是静态设计来配置和组织相关的东西吗?
- 在 Angular 模块中涉及动态逻辑代码,可能写在模块类的构造函数中,不是最佳实践吗?
解决方案
我认为主要区别在于 Angular 组件、模块和服务使用 Angular 包中的装饰器。
例如@Component()
这样做:
* Component decorator allows you to mark a class as an Angular component and provide additional
* metadata that determines how the component should be processed, instantiated and used at
* runtime.
这直接来自您可以查找的源代码。
您传递给它的东西也非常特定于角度。除此之外,不应该没有太大的区别。
如果您与需要初始化的组件交互,则不应使用 JS 构造函数。它的执行时间会稍早一些ngOnInit
,并且可能会导致问题,因为这就是 Angular 的工作方式。
如果您编写自定义模块,那么您当然可以按常规进行操作。
初始化模块的一种方法是forRoot
约定:
在这里,您基本上创建了一个具有给定配置的单例:(取自链接)
src/app/core/user.service.ts(构造函数)
constructor(@Optional() config: UserServiceConfig) {
if (config) { this._userName = config.userName; }
}
src/app/core/core.module.ts (forRoot)
static forRoot(config: UserServiceConfig): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
{provide: UserServiceConfig, useValue: config }
]
};
}
src/app/app.module.ts(导入)
import { CoreModule } from './core/core.module';
/* . . . */
@NgModule({
imports: [
BrowserModule,
ContactModule,
CoreModule.forRoot({userName: 'Miss Marple'}),
AppRoutingModule
],
/* . . . */
})
export class AppModule { }
推荐阅读
- python - 使用 Python 从文本表中提取数据
- python - 如何将 makefile 重写为 distutils.core.Extension
- sharepoint - 如何在 SharePoint Online 现代网站中自定义列表/库的列标题或为其设置样式?
- azure-devops - 如何防止直接推送到 AzureDevOps 中的 Master 分支
- bash - 查找和替换非 utf8 字符
- python - 在 Python / Cython / Numpy 中计算 2 个二进制向量之间的汉明距离的最快方法
- cognos - cognos analytics 11 中的上传文件位置在哪里?
- sql - 关键字“PIVOT”附近的语法不正确
- webusb - WebUSB .claimInterface 永远不会在 Windows 上返回
- c - C 中的 pthreads:如何阻止线程相互干扰?