2016-09-06 53 views
5

我有一個名爲CalculationService的服務,它被聲明爲@Injectable()。該服務使用了大量其他注入類,每個注入類也被聲明爲@Injectable(),並通過@Inject()向CalculationService的構造函數提供。Angular 2 - 作爲NgModule的服務不必聲明所有提供者?

現在,當我想用​​我的應用程序內的服務,AppComponent看起來像這樣(爲方便起見,我省略了打字稿進口):

@NgModule({ 
    declarations: [AppComponent], 
    imports: [ 
    BrowserModule, 
    RouterModule.forRoot(routeConfig), 
    PlannerModule 
    ], 
    providers: [ 
    InputService, 
    Bausparen, 
    BausparenInput, 
    Girokonto, 
    GirokontoInput, 
    Immobilien, 
    ImmobilienInput, 
    Lebensversicherung, 
    LebensversicherungInput, 
    Rentenversicherung, 
    RentenversicherungInput, 
    Tagesgeld, 
    TagesgeldInput, 
    Termingeld, 
    TermingeldInput, 
    Wertpapiere, 
    WertpapiereInput 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 
} 

我不需要訪問所有這些提供者直接在應用程序模塊中聲明。唯一需要的類是CalculationService,但我不知道如何在服務中聲明提供者。

有沒有辦法將服務重構爲模塊,即在CalculationService中聲明提供者?或者我必須擺脫所有@Injectable()(Bausparen等)並在計算服務中創建對象,以便不需要提供者?

回答

3

您不能在服務器上或在服務中註冊提供者。您只能在模塊或組件中註冊它們。

您可以做的是爲您的服務創建一個模塊,然後您只需將模塊添加到imports: [...]並且所有提供者都在全球註冊。

如果您需要實現並導入forRoot()

+0

當我宣佈我的服務爲NgModule,然後要放什麼'declarations'和'bootstrap'延遲加載的模塊? –

+1

其實我沒有嘗試過沒有'declarations'模塊的模塊,但我會盡量忽略'declarations'和'bootstrap'。 –

相關問題