Angular 模块应该是空 JavaScript 模块吗?

Should the Angular Module be a Empty JavaScript Module?

我正在学习Angular 7。我目前清楚 Angular 中的引导设计和元数据对象使用标记 angular 组件和模块。但是,我仍然没有看到 angular 模块不为空 class 的示例或案例。

所以,我目前想知道:

我认为主要区别在于 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.

这是直接来自您可以查找的源代码。

您传递给这里的东西也非常 angular 特定。除此之外,不应该有很大的区别。

如果您与需要初始化的组件进行交互,则不应使用 JS 构造函数。它会比 ngOnInit 稍早执行,并且可能会导致问题,因为这是 angular 的工作方式。

如果您编写自定义模块,那么您当然可以按常规做事。

一种初始化模块的方法是 forRoot convention: 在这里,您基本上创建了一个具有给定配置的单例: (摘自link)

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 { }