首页 > 解决方案 > Angular 模块应该是一个空的 JavaScript 模块吗?

问题描述

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

所以,我目前想知道:

标签: javascriptangularangular7

解决方案


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

推荐阅读