千木郷
千木郷

Reputation: 1817

Should the Angular Module be a Empty JavaScript Module?

I'm now learning Angular 7. I'm currently clear about the bootstrapping design in Angular and the metadata object usage marking angular components and modules. However, I've still not seen an example or a case where angular module is not an empty class.

So, I'm currently wonder that:

Upvotes: 1

Views: 422

Answers (1)

mchl18
mchl18

Reputation: 2336

I would think the main difference is that Angular components, modules and services use decorators from the angular package.

E.g. @Component() does this:

 * 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.

This is straight from the source code which you can look up.

The things you pass into this is also quite angular-specific. Other than that, no there should not be a big difference.

If you interface with a component which needs initialization, you should not use the JS constructor. It will execute slightly earlier than ngOnInit and could cause problems since this is how angular works.

If you write custom modules then you can of course just do things conventionally.

A way to initialize modules is the forRoot convention: Here you basically create a singleton with a given configuration: (taken from the link)

src/app/core/user.service.ts (constructor)

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 (imports)

import { CoreModule } from './core/core.module';
/* . . . */
@NgModule({
  imports: [
    BrowserModule,
    ContactModule,
    CoreModule.forRoot({userName: 'Miss Marple'}),
    AppRoutingModule
  ],
/* . . . */
})
export class AppModule { }

Upvotes: 1

Related Questions