我建议您将所有这些服务加入一个模数并将其导入您的组件模块。一个可能的结构可以是这样
services/
|-one.service.ts
|-two.service.ts
|-three.service.ts
|-four.service.ts
|-services.module.ts
your-module/
|-your-component.component.css
|-your-component.component.html
|-your-component.component.ts
|-your-module.module.ts
app.component.css
app.component.html
app.component.ts
app.module.ts
在此示例中,您有四个服务和 services.module.ts,如下所示
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { OneService } from './one.service.ts'
import { TwoService } from './two.service.ts'
import { ThreeService } from './three.service.ts'
import { FourService } from './four.service.ts'
@NgModule({
declarations: [],
imports: [
CommonModule,
],
providers : [
OneService,
TwoService,
ThreeService,
FourService
]
})
export class ServicesModule { }
export * from './one.service';
export * from './two.service';
export * from './three.service';
export * from './four.service';
然后在 your-moudle.module.ts
import { ServiceModule } from '../services/services.module';
...
...
imports : [
...
...
ServiceModule
]
...
...
最后在 your-component.component.ts
import { OneService, TwoService, ThreeService, FourService } from '../../services/services.module'
...
...
constructor(
private _oneService : OneService,
private _twoService : TwoService,
private _threeService : ThreeService,
private _fourService : FourService
) {}
...
...
您还可以为 tsconfig.json 添加别名以避免相对路径
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@services" : [
"app/services/services.module.ts"
],
},
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}
然后您可以按如下方式导入服务
import { OneService, TwoService, ThreeService, FourService } from '@services'
希望这可以帮到你。