Artur K.
Artur K.

Reputation: 3309

How can a feature module with providers be imported to another feature module with providers?

There's a feature module that I kind of like or which I would like to use as a part of my own feature module. The sub-module that I want to include is called SlimLoadingBarModule. I want to use it as a base and use it's functionality by providing my own on the top of it. Additionally my whole app can use my LoadingBarComponent and LoadingBarService and don't need to know about the underlying providers.

So in the end I would like to be able to inject it in my service like this:

@Injectable()
export class LoadingBarService {

    constructor(private slimLoadingBarService: SlimLoadingBarService) {}

    start() {}

    finish() {}

    /**/ 

}

And for that I must somehow include it in my module

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

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

import { LoadingBarComponent } from './loading-bar.component';
import { LoadingBarService } from './loading-bar.service';

@NgModule({
    imports: [ SlimLoadingBarModule.forRoot() ],
    declarations: [ LoadingBarComponent ],
    exports: [ LoadingBarComponent ]
})
export class LoadingBarModule {

    static forRoot(): ModuleWithProviders {
        return {
            ngModule: LoadingBarModule,
            providers: [ LoadingBarService ]
        };
    }

}

And the template simply contains the tag for SlimLoadingBar


Problem

Although my own service is singleton throughout my modules, I can't make the SlimLoadingBarService to be a singleton. I always get exactly two instances and if I don't inject it into my service I get 1, but then I can't use it.

Additionally I know my service and component is working, as I got these to work once somehow, but I didn't find the modules and imports to be logical enough to keep them like this.

I Have tried various solutions, through SharedModule, through AppModule but whatever I seem to do, when I try to inject it into my LoadingBarService I have 2 instances!

But I feel it shouldn't be impossible for a feature module to use some additional underlying providers and perhaps hiding them from the rest of the application? Is it even possible? If so, then what am I doing wrong?

Upvotes: 2

Views: 5090

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

forRoot() should only be used in AppModule

@NgModule({
    imports: [ SlimLoadingBarModule.forRoot() ],

https://angular.io/docs/ts/latest/guide/ngmodule.html#!#core-for-root

Call forRoot only in the root application module, AppModule. Calling it in any other module, particularly in a lazy loaded module, is contrary to the intent and is likely to produce a runtime error.

Remember to import the result; don't add it to any other @NgModule list.

Upvotes: 3

Related Questions