Reputation: 8958
I'm trying to clean up my code and minimize all the import code that I have to setup everywhere.
So in index.ts
in my services folder I set up a barell:
import { Service1} from "./service1.service";
import { Service2 } from "./service2.service";
import { Service3 } from "./service3.service";
export const commonServices = [
Service1,
Service2,
Service3,
];
So that I can minimize the import code in app.module.ts
using the spread operator.
...
import { commonServices } from "./common/services";
@NgModule({
...
providers: [
...commonServices,
]
})
export class AppModule { }
But in some.component.ts
, I can't use a single import since index.ts
doesn't barrel the specific services as well.
...
// This doesn't work
// import { Service1, Service2 } from "../../core/services";
// I have to do this
import { Service1 } from "../../core/services/service1.service";
import { Service2 } from "../../core/services/service2.service";
@Component({
})
export class SomeComponent {
}
How can I setup index.ts
to also export the names of the services, is there a nice clean way to achieve this?
Upvotes: 3
Views: 1225
Reputation: 41294
You can do this:
// index.ts
export { Service1} from "./service1.service";
export { Service2 } from "./service2.service";
export { Service3 } from "./service3.service";
// app.module.ts
import * as commonServices from "./common/services";
...
providers: [
Object.keys(commonServices).map(svc => commonServices[svc]),
]
// some.component.ts
import { Service1, Service2 } from "../../core/services";
Note, you don't need to spread commonServices, Angular does that automatically, in fact it could be any nested array, e.g. [Service1, [Service2], [[[Service3]]]]
, Angular will flatten all that.
Upvotes: 4