Answer the question
In order to leave comments, you need to log in
Angular 2 how to properly set dependencies for singleton service in bootstrap?
So, for the 3rd day I have been struggling with the problem, I have already asked on SO, but so far no one has helped me.
Let's say there are 2 singleton services (ServiceA and ServiceB) - stores that store data throughout the entire life cycle of the application.
These two services have a dependency in the constructor - CollectionService. These 2 services forward data through themselves into this collection, in which the data is already stored. Accordingly, for each of these 2 services, the collection must be its own, i.e. must not be a singleton .
To complicate matters, one of the services, ServiceA, must be available with a correctly injected dependency inside the RouteHook's CanActivate.
And here the problem arises - how to resolve this whole thing through bootstrap ()?
I tried to do as stated in the documentation using useFactory. One caveat - the docks show an example of creating an object without constructor parameters, in my case I add a collection as a dependency.
imports ...
bootstrap(AppComponent, [
provide(ServiceA, {
useFactory: () => {
rerturn new ServiceA(new CollectionService<ServiceADataType>())
}
}),
provide(ServiceB, {
useFactory: () => {
rerturn new ServiceB(new CollectionService<ServiceBDataType>())
}
})
]);
Cannot read property 'getOptional' of undefined
deps: [CollectionService]
error : then you need to specify the CollectionService directly in bootstrap, and then the collection will become a singleton. providers: [ServiceA, CollectionService]
export const AppInjector = (injector?: Injector): Injector => {
if (injector) {
appInjectorRef = injector;
}
return appInjectorRef;
};
bootstrap(AppComponent, [
...
]).then((appRef: ComponentRef) => {
AppInjector(appRef.injector);
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question