1

How can i have a global provider that is initialized just once. So i have the following provider

@Injectable()
export class ApiRequest {

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

And then a shared module

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

export class SharedModule {

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

The code is working, the issue here is that the ApiRequest constructor is initialized each time i am changing the route, so each page change. How can i make the ApiRequest provider to be initialized just once in the entire application?

keepwalking
  • 2,644
  • 6
  • 28
  • 63
  • Sounds like the module is lazy loaded. In this case you need to implement `forRoot()` https://angular.io/docs/ts/latest/guide/ngmodule.html, https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html – Günter Zöchbauer Sep 06 '16 at 12:33
  • @GünterZöchbauer tried that as well. Same issue. Edited the question to use forRoot – keepwalking Sep 06 '16 at 12:36
  • I think I saw such an issue. That should be fixed in master and included with the next release. – Günter Zöchbauer Sep 06 '16 at 12:40
  • So its nothing i can do right? Also i saw that the main component of the router is also executed each time i am changing the page although i am changing its children. – keepwalking Sep 06 '16 at 12:41
  • I guess not. Sorry, don't know about the other issue. – Günter Zöchbauer Sep 06 '16 at 12:43
  • So it looks like if i declare the Provider in a Sub module its initialized each time in its components. If i declare the provider in the map module it works in submodules and it get initialized only once. – keepwalking Sep 06 '16 at 15:18

1 Answers1

0

So the issues here is that i was declaring the provider in a submodule. Even tough i was using the provider only in the submodule it was still initializing on each injection. So i had to declare it in the main module and it works as expected.

keepwalking
  • 2,644
  • 6
  • 28
  • 63
  • This should only be an issue when the module is lazy loaded. You might want to use a core module as mentioned in http://stackoverflow.com/questions/39447443/angular-2-difference-between-core-and-feature-modules – Günter Zöchbauer Sep 12 '16 at 10:07
  • Tried that, same issue. Unless i declare it in the main module i get the same results if module is or is not lazy loaded. – keepwalking Sep 12 '16 at 10:19