'How do I export services in a module?
How can I export a service from a module in angular 2?
The idea is that when I import into another component, I want the import to be agnostic of the actual service location, it should be the repsonsibility of the module to manage that
Core.module.ts:
import {
NgModule,
Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyApi } from './Api/myApi.service';
import { AuthenticationModule } from './authentication/authentication.module';
@NgModule({
imports: [
CommonModule,
AuthenticationModule
],
providers: [
MyApi
],
exports: [MyApi, AuthenticationModule]
})
export class CoreModule {
constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error(
'CoreModule is already loaded. Import it in the AppModule only');
}
}
}
App.component.ts:
import { Router, ActivatedRoute } from '@angular/router';
import { Component, ViewContainerRef, OnInit } from '@angular/core';
import { MyApi } from 'core.module'; //i want this to be the core module import, not './core/api/myApi.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor ( public service: MyApi) {
service.doStuff()
}
}
But in the code example above, it tells me that MyApi isn't exported by Core.module.
This is slightly pseudo-code, so excuse the small errors I've made :)
Solution 1:[1]
There's two things you can do to make your imports more concise:
You can export everything from your entry point file (by convention is often called
index.ts) and later import any class you've exported from that file:import { NgModule } from '@angular/core'; import { ApiService } from 'path/to/api.service'; @NgModule({ ... }) export class CoreModule {} export * from 'path/to/api.service';This way you can then import both
CoreModuleandApiServicefrom the same route like this:import { CoreModule, ApiService } from 'path/to/core.module;'So you have a common entry point for all your module dependencies.
If your module is deeply nested, or you want to import it from a location that might end up in going back and forth a few directories, you can always create an alias for that path in your main
tsconfig.jsonfile, undercompilerOptions.paths:{ "compilerOptions": { // ... "paths": { "@app-core": ["app/path/to/deeply/nested/core.module"] } } }And then use that alias instead:
import { CoreModule, ApiService } from '@app-core'
Solution 2:[2]
You have to add this line into your core.module
export {MyApi} from './Api/myApi.service';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Osman Cea |
| Solution 2 | Bunyamin Coskuner |
