2016-10-17 4 views
1

私は自分のコードを整理し、どこにでも設定しなければならないすべてのインポートコードを最小化しようとしています。私はスプレッド演算子を使用してapp.module.tsで輸入コードを最小限に抑えることができるように角2、インポートのためにスプレッドとバレルを組み合わせる

import { Service1} from "./service1.service"; 
import { Service2 } from "./service2.service"; 
import { Service3 } from "./service3.service"; 

export const commonServices = [ 
    Service1, 
    Service2, 
    Service3, 
]; 

は、だから私のサービスフォルダにindex.tsに私がbarellを設定します。

... 

import { commonServices } from "./common/services"; 

@NgModule({ 
    ... 
    providers: [ 
     ...commonServices, 
    ] 
}) 

export class AppModule { } 

しかしindex.tsは同様にバレル特定のサービスをしていないためsome.component.tsで、私は1つのインポートを使用することはできません。

... 

// 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、これを達成するための良いクリーンな方法はありますか?

答えて

2

あなたがこれを行うことができます:

// 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を広めるために必要がない、角度は自動的に、実際には、例えば、任意のネストされた配列にすることができることを行います[Service1, [Service2], [[[Service3]]]]、Angularはすべてを平坦化します。

+0

これを 'commonServices'エクスポートとどのように組み合わせればいいですか?つまり、 'index.ts'のすべてのサービスをインポートしてエクスポートする必要がありますか? – Joel

+0

commonServicesをまったくエクスポートしないでください。** commonServicesとして 'index.ts' **を全部インポートしてください(これは、ちょうど1つの場所にあり、手動でインポートすることもできます)。 – Sasxa

+0

ああ、私がそれを得るのを待つ..あなたが 'commonServicesとしてimport *すると、あなたはオブジェクトcommonServices.Service1、commonServices.Service2を得るでしょう...それを配列に変換してから、' providers [] 'で使用してください。 – Sasxa

関連する問題