We know that in root module provider we can set an APP_INITIALIZER
that bootstrap some dependencies in the backend and then loads the first component
{
provide: APP_INITIALIZER,
useFactory: configLoader,
multi: true,
deps: [ConfigService]
}
I will load my user configs before the app starts in the above way, but I want to do somehing more, like connect websocket before my app starts.
I know that I can do in in configLoader
function that I wrote, that first load configs and then connect websocket in that configLoader function, but for some reasons, I can't do that right now, so I need do in in someway like this:
{
provide: APP_INITIALIZER,
useFactory: [configLoader, websocketLoader],
multi: true,
deps: [ConfigService, WebsocketService]
}
But unfortunately, it won't work. So is there any way to load multiple app initializers?
Multi Providers in APP_INITIALIZERYou can use the multi: true to create Multi Provider token. This means we can create more than one function/service and invoke it during initialization.
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.
useFactory
isn't supposed to be an array
{
provide: APP_INITIALIZER,
useFactory: websocketLoader,
multi: true,
deps: [ConfigService, WebsocketService]
},
{
provide: APP_INITIALIZER,
useFactory: configLoader,
multi: true,
deps: [ConfigService, WebsocketService]
}
With multi: true
providing multiple providers with the same key (APP_INITIALIZER
) won't override the previous one (behavior with multi: false
), but DI will collect them in an array itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With