[英]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.