2016-08-12 52 views
3

如何在使用NgModule的新功能時設置全局提供程序?在過去,我可以這樣做:如何在Angular2 2.0.0 RC.5中設置全局提供者?

bootstrap(AppComponent, [ 
    GlobalServiceAAA, 
    GLOBAL_PROVIDERS_BBB 
]); 

使用NgModule我們引導應用詮釋他的方式:

platformBrowserDynamic().bootstrapModule(AppModule); 

其中在這種情況下,我把我的全球服務和供應商(假設我不想在每個組件中提供它們)?

回答

3

有兩種方法可以做到這一點。

注意:共享功能模塊可能包含您的通用服務。

1.無shared feature module

@NgModule({ 
    (...) 
    providers: [ // <------- 
    GlobalServiceAAA, GLOBAL_PROVIDERS_BBB 
    ] 
}) 
export class AppModule { } 

2. shared feature module

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppComponent } from './app.component'; 

import {SharedModule} from './shared/shared.module';  //<-------- Important 

... 
... 


@NgModule({ 
    imports:  [ BrowserModule, 
        SharedModule.forRoot(),     //<----------Important 
        HomeModule, 
        routing 
       ], 
    declarations: [ AppComponent], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

shared.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core'; 
import { CommonModule }  from '@angular/common'; 

import { GlobalServiceAAA} from './path'     //<-------- important 
import { GLOBAL_PROVIDERS_BBB} from './path';   //<-------- important 
@NgModule({ 
    imports:  [ CommonModule ], 
    declarations: [], 
    exports:  [ CommonModule ] 
}) 
export class SharedModule { 
    static forRoot(): ModuleWithProviders { 
    return { 
     ngModule: SharedModule, 
     providers: [ GlobalServiceAAA,GLOBAL_PROVIDERS_BBB] //<------important 
    }; 
    } 
} 
4

您需要在NgModule的providers屬性中指定它們。

@NgModule({ 
    (...) 
    providers: [ // <------- 
    GlobalServiceAAA, GLOBAL_PROVIDERS_BBB 
    ] 
}) 
export class AppModule { }