angularangular2-routingangular2-providers

Angular 2 RC 5 global provider


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?


Solution

  • 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.