[英]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: 所以在我的services文件夹中的
index.ts
中,我设置了一个简单的:
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. 这样我就可以使用spread运算符最小化
app.module.ts
的导入代码。
...
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. 但是在
some.component.ts
,我不能使用单个导入,因为index.ts
也没有使用特定的服务。
...
// 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? 如何设置
index.ts
以导出服务的名称,有没有一个很好的干净方法来实现这一目标?
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. 注意,你不需要传播commonServices ,Angular会自动执行,实际上它可以是任何嵌套数组,例如
[Service1, [Service2], [[[Service3]]]]
,Angular会将所有这些[Service1, [Service2], [[[Service3]]]]
平。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.