Reputation: 307
I have a lot of code, but I'll try to cut it down. I am trying to transform a service into a singleton service (TagService). But this seems to be causing problems. I have lots of components and services, but I'll simplify it down to AddGroupComponent, TagComponent, TagService and ApiService.
To create a singleton TagService, I added it to app.module.ts:
import {TagService} from './services/TagService';
const appRoutes: Routes = [
...
];
@NgModule({
declarations: [
TagComponent,
...
],
imports: [
...
],
entryComponents: [AddGroupComponent, ... ]
providers: [TagService], // added this here
})
export class AppModule {
}
This is my TagService, I didn't change anything here:
import {ApiService} from '../ApiService/ApiService';
@Injectable()
export class TagService {
constructor(private api: ApiService) {
....
}
And these are some of the components where I want to use the TagService as a shared singleton.
// Didn't change anything here
@Component({
...
providers: []
})
export class TagComponent {
constructor(private api: ApiService, private tagService: TagService) {
super();
}
AddGroupComponent
@Component({
...
providers: [ApiService, PermissionsService] // I removed TagService from here
})
export class AddGroupComponent {
constructor(private api: ApiService, private tagService: TagService) {
...
}
With this I get error:
AddGroupComponent_Host.ngfactory.js? [sm]:1 ERROR Error: StaticInjectorError(MgrModule)[TagsComponent -> ApiService]: StaticInjectorError(Platform: core)[TagsComponent -> ApiService]: NullInjectorError: No provider for ApiService!
I understand that it doesn't have provider. It seems to me like all of the TagComponents are already using ApiService as a singleton (it's only created once). But I'm not really sure what is going on.
EDIT:
I added ApiService to ngModule providers and removed it from other providers. Now everything works, but I added console.logs to my service constructors and when I press the button to create AddGroupComponent, a new ApiService and TagService are still created (but just, when I press it many times, they are not created again). So right now it creates them twice (once when loading page and second time when clicking the button that opens the AddGroupComponent.
EDIT 2:
Nevermind, I had another file called app.component.ts which had a generic MgrComponent which also had those services as providers. Seems like everything is working now.
Upvotes: 0
Views: 90