9

I'm trying to make a shared module, but it's don't want to work somehow.

The shared module looks like this:

import { ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SharedMetaModule } from './shared-meta';
import { ApplicationState } from './state/application-state';
import { MilitaryTimePipe } from './pipes/military-time-pipe';
import { KeysPipe } from './pipes/object-pipe';
import { GirlsClass } from './advertisers/girls';

@NgModule({
    imports: [CommonModule],
    declarations: [
        KeysPipe,
        MilitaryTimePipe
    ],
    exports: [
        SharedMetaModule,
        KeysPipe,
        MilitaryTimePipe
    ],
    providers: [ApplicationState]
})
export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return { ngModule: SharedModule };
    }
}

I have an app.module.ts like this:

import { SharedModule } from '@shared/shared.module';
@NgModule({
    imports: [
        ...
        SharedModule.forRoot(),

Then I have a profile-gallery.module.ts where a pipe from the shared module would be used.

If I don't import the shared module in the profile-gallery module I got this error:

The pipe 'keys' could not be found.

If I import the shared module to the profile-gallery module I got this error:

MetaModule already loaded; import in root module only.

How could work the shared module in this situation?

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
user8778731
  • 155
  • 1
  • 2
  • 9

1 Answers1

8

The purpose of a Shared module is to import it in all the required modules, more than once. So there is no need for the forRoot method that makes sure it's imported only once.

Remove the forRoot method entirely and import the module where needed:

import { SharedModule } from '@shared/shared.module';
@NgModule({
    imports: [
        ...
        SharedModule,
Adrian Fâciu
  • 12,414
  • 3
  • 53
  • 68
  • Thanks! If i delete the forRoot method from the app.module imports i still have this error: `Uncaught (in promise): Error: MetaModule already loaded; import in root module only.` If i delete the shared module from the app.module, i have errors because the pipe (i'm actually refactoring the app to modules with lazy loading) If i delete the SharedMetaModule from the SharedModule, then i have to import it individually in every module. I dont know what would be the best option :( – user8778731 May 06 '18 at 19:54
  • You might have a naming error between SharedMetaModule <-> MetaModule – Jens Habegger May 06 '18 at 19:57
  • The SharedModule's imports the MetaModule: `imports: [ MetaModule.forRoot({ provide: MetaLoader, useFactory: metaFactory, deps: [] }) ]` – user8778731 May 06 '18 at 20:08
  • At the end i separed out the MetaModule from the SharedModule, and imported the MetaModule in the app.module, then now it looks fine. – user8778731 May 06 '18 at 21:18