Angular2 Module: How can i import a service from another module
Asked Answered
H

1

29
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { ClinicFacilityService } from './apiClient.module';


@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  declarations: [
    DailyScheduleComponent,
  ],
  providers: [
    ClinicFacilityService
  ],
  exports: [
    DailyScheduleComponent
  ],
})
export class ClinicDashboardModule {
}

I need to import ClinicFacilityService that is declared in another module (apiClient.module)

Is this even possible, if not why is not possible. At the moment i am importing ClinicFacilityService like this:

import { ClinicFacilityService } from './api-client-service/clinic-facility.service';
Hedda answered 3/11, 2016 at 7:36 Comment(2)
This is kinda old post but for the sake of others, I find this article very comprehensive and fully answers this question. Hint: see Importing services section of that article.Seymour
The answer to this depends on how the service is injected in the service file itselfWagonage
L
38

Adding the module to imports should do

import { ApiClientModule } from './apiClient.module';

@NgModule({
  imports: [
    ApiClientModule,
    CommonModule,
    FormsModule
  ],
  declarations: [
    DailyScheduleComponent,
  ],
  exports: [
    DailyScheduleComponent
  ],
})
export class ClinicDashboardModule {
}

otherwise import the file that contains the service class

import { ClinicFacilityService } from './clinic-facility.service';

There is a clear distinction between @NgModule() imports and TypeScript imports.

If you need to use the class name (ClinicFacilityService) then a TypeScript import of that class is required. This is entirely unrelated to @NgModule()

@NgModule({
  ...
  providers: [
    ClinicFacilityService
  ],

If the @NgModule() import is required, then the class name of the module class (ApiClientModule) requires a TypeScript import because the module needs to be passed.

@NgModule({
  imports: [
    ApiClientModule,
  ],
  • TypeScript imports are to to uniquely identify a class.
  • NgModule imports are to define that a module depends on another module.
Lukas answered 3/11, 2016 at 7:38 Comment(4)
Glad to hear :)Contributor
Very helpful information, re: difference between Angular import and TypeScript importAeromancy
@GünterZöchbauer I am not clear here. Are you saying, you can basically keep the service file as it is in feature module and still use it in the importing module?Asphaltite
I think it would be best if you would create a new question where you explain what you try to accomplish, what you tried, and what exactly didn't work as you expected.Contributor

© 2022 - 2024 — McMap. All rights reserved.