[英]Angular 2, combine spread and barrel for imports
我正在尝试清理我的代码并最小化我必须在任何地方设置的所有导入代码。
所以在我的services文件夹中的index.ts
中,我设置了一个简单的:
import { Service1} from "./service1.service";
import { Service2 } from "./service2.service";
import { Service3 } from "./service3.service";
export const commonServices = [
Service1,
Service2,
Service3,
];
这样我就可以使用spread运算符最小化app.module.ts
的导入代码。
...
import { commonServices } from "./common/services";
@NgModule({
...
providers: [
...commonServices,
]
})
export class AppModule { }
但是在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 {
}
如何设置index.ts
以导出服务的名称,有没有一个很好的干净方法来实现这一目标?
你可以这样做:
// 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";
注意,你不需要传播commonServices ,Angular会自动执行,实际上它可以是任何嵌套数组,例如[Service1, [Service2], [[[Service3]]]]
,Angular会将所有这些[Service1, [Service2], [[[Service3]]]]
平。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.