Home > Software engineering >  Angular use a service provided in a shared module not recognizing the injectable
Angular use a service provided in a shared module not recognizing the injectable

Time:01-18

Meet SharedModule, it is importing and exporting several modules:

@NgModule({
  declarations: [PlatformSwitchPageComponent],
  imports: [
    CommonModule,
    MyApiModule,
  ],
  exports: [
    MyApiModule
  ]
})
export class SharedModule { }

MyApiModule is another module that contains a few modules related to my Api:

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    FileChunkUploaderModule,
    FileDownloaderModule,
    SessionClientModule,
  ],
  exports: [
    FileChunkUploaderModule,
    FileDownloaderModule,
    SessionClientModule
  ]
})
export class MyApiModule{ }

Now, SessionClientModule is a module that provides a service:

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
  ],
  providers: [SessionClient],
})
export class SessionClientModule {
}

Now you can't really export a service, since it's not a pipe or a directive or a component.

So here comes the PagesModule which contains the pages of the application, where each page is a module of on its own:

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    LandingModule,
    SharedModule,
    ExampleModule
  ],
  exports: [
    LandingModule,
    ExampleModule
  ]
})
export class PagesModule { }

Now, PageaModule is imported in AppModule and is used in the router for lazy-loading by routes:

const routes: Routes = [
  {
    path: '',
    component: LandingComponent,
  },
  {
    path: 'session/:id',
    component: ExampleModule
  }
];

In ExampleModule I provide a service called MyService:

@NgModule({
  declarations: [ExampleComponent, DesktopFileTransferLayoutComponent],
  imports: [
    CommonModule,
    SharedModule
  ],
  providers: [MyService],
  exports: [ExampleComponent]
})
export class ExampleModule { }

and MyService injects in itself SessionClient service which is part of SessionClientModule exported in MyApiModule which is exported in SharedModule.

Now I get the following error when using it:

core.js:4197 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[MyService -> SessionClient -> SessionClient -> SessionClient]: 

If SharedModule is imported in PagesModule, why doesn't it recognize the service I am trying to use?

Latest version of angular

CodePudding user response:

if you create a service with @Injectable({ providedIn: 'root' }) you don't need to declare the service in any providers and it will be avaliable everywhere (just add it in the constructor)

  •  Tags:  
  • Related