2016-09-06 83 views
1

我如何擁有一個初始化一次的全球供應商? 所以我有以下提供商Angular 2 RC 5全球供應商

@Injectable() 
export class ApiRequest { 

    http: Http; 
    constructor(@Inject(Http) http) { 
     console.log('Test'); 
    } 
} 

然後共享模塊

@NgModule({ 
    imports: [BrowserModule, 
     HttpModule], 
    declarations: [ControlMessage, InfiniteScroll], 
    entryComponents: [ControlMessage], 
    providers: [ApiRequest], 
    exports: [ControlMessage, InfiniteScroll], 
}) 

出口類SharedModule {

static forRoot(): ModuleWithProviders { 
    return { 
     ngModule: SharedModule, 
     providers: [ApiRequest] 
    }; 
} 

的代碼工作,這裏的問題是,ApiRequest構造每次我改變路線時都會初始化,所以每一頁都會改變。我怎樣才能讓ApiRequest提供者在整個應用程序中初始化一次?

+0

聲音就像模塊是懶加載的。在這種情況下,您需要實現'forRoot()'https://angular.io/docs/ts/latest/guide/ngmodule.html,https://angular.io/docs/ts/latest/cookbook/rc4- to-rc5.html –

+0

@GünterZöchbauer也嘗試過。同樣的問題。編輯該問題使用forRoot – keepwalking

+0

我想我看到了這樣的問題。這應該在主版本中修復幷包含在下一版本中。 –

回答

0

所以這裏的問題是我在一個子模塊中聲明提供者。即使很難,我只在子模塊中使用提供程序,但它在每次注入時仍在初始化。所以我不得不在主模塊中聲明它,它按預期工作。

+0

這應該只是當模塊被延遲加載時的一個問題。您可能需要使用http://stackoverflow.com/questions/39447443/angular-2-difference-between-core-and-feature-modules –

+0

中提到的核心模塊。試過這個問題。除非我在主模塊中聲明它,否則如果模塊是或不是惰性加載的,我會得到相同的結果。 – keepwalking