简体   繁体   中英

Angular 2, combine spread and barrel for imports

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?

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, eg [Service1, [Service2], [[[Service3]]]] , Angular will flatten all that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM