Reputation: 5724
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 :)
Upvotes: 15
Views: 20554
Reputation: 1467
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 CoreModule
and ApiService
from 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.json
file, under compilerOptions.paths
:
{
"compilerOptions": {
// ...
"paths": {
"@app-core": ["app/path/to/deeply/nested/core.module"]
}
}
}
And then use that alias instead:
import { CoreModule, ApiService } from '@app-core'
Upvotes: 8
Reputation: 8859
You have to add this line into your core.module
export {MyApi} from './Api/myApi.service';
Upvotes: 1