如何从 Angular 2 中的模块导出服务?
这个想法是,当我导入另一个组件时,我希望导入不知道实际的服务位置,应该是模块的责任来管理它
核心模块.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()
}
}
但在上面的代码示例中,它告诉我 MyApi 不是由 Core.module 导出的。
这有点伪代码,所以请原谅我犯的小错误:)
最佳答案
你可以做两件事来让你的导入更简洁:
index.ts
),然后导入您从该文件中导出的任何类:import { NgModule } from '@angular/core';
import { ApiService } from 'path/to/api.service';
@NgModule({ ... })
export class CoreModule {}
export * from 'path/to/api.service';
这样您就可以同时导入
CoreModule
和 ApiService
从这样的同一条路线:import { CoreModule, ApiService } from 'path/to/core.module;'
因此,您对所有模块依赖项都有一个共同的入口点。
tsconfig.json
中为该路径创建一个别名。文件,在 compilerOptions.paths
下:{
"compilerOptions": {
// ...
"paths": {
"@app-core": ["app/path/to/deeply/nested/core.module"]
}
}
}
然后改用该别名:
import { CoreModule, ApiService } from '@app-core'
关于angular - 如何在模块中导出服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906113/