2017-11-07 8 views
0

に動的プロバイダサービスベースを作成すると、 'TestService'などのuseFactoryで動的プロバイダを作成したいと考えています。 paramsが 'A'の場合、プロバイダーは 'TestServiceA'、paramsが 'B'ならプロバイダは 'TestServiceB'angular2 +以下のようにパラメータ

どのようにする必要がありますか?おかげ

https://plnkr.co/edit/8JDopoVCmKSPaQxk0iJH?p=preview

export class App { 
    type: string = 'A'; 

    text:string; 
    constructor(
    @Inject('TestService') private testService 
) { 
    this.text = this.testService.test(); 
    } 
} 

答えて

0

あなたは、工場からの関数を返し

export function testServiceFactory2() { 
    return (serviceType) => { 
    return serviceType === 'A' 
     ? new TestServiceA() 
     : new TestServiceB() 
    } 
} 

この

providers: [ 
    {provide: 'TestService', useFactory: testServiceFactory2} 
] 


constructor(@Inject('TestService') private testService) { 
    // this.text = this.testService.test(); 
    this.text = this.testService(this.type).test(); 
} 
+0

こんにちは、おかげであなたの答えのようにそれを使用することができます。それは動作しますが、2回 'this.testService(this.type)'を使用すると、testServiceFactoryが2つのTestServiceAまたはTestServiceBサービスを作成するという別の問題が見つかりました。あなたは私のプランナーのURLでそれを見ることができます。 – dyh333

+0

興味深い、私は見てみましょう。 –

+0

まあ、私は何を言いたいのか分からない。それはあなたの***工場でした。私はちょうどそれをparamatizeする方法を示した。あなたは 'new()'をファクトリに入れて、ファクトリを2回コールします。他の結果は表示されません。もちろん、2つのインスタンスがあります。シングルトンが必要な場合は、工場でシングルトンをコーディングしてください! –

関連する問題