I would like to set up a factory that does async work to return a service, and then provide that factory to a factory provider to provide that service to a component when it loa
It seems Angular cannot implement the async factory function for the provider directly.
In order to do this, we need to set up a new function and hand it over to the NgModule
to do the APP_INITIALIZER job.
import {
APP_INITIALIZER,
} from '@angular/core'
function configFactory(testService: TestService) {
// do the async tasks at here
return () => testService.init()
}
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useFactory: configFactory,
deps: [TestService],
multi: true,
},
],
})
Angular4 APP_INITIALIZER won't delay initialization
you can make your promise function to be async
export function testFactory(auth: any, temp: any) {
return new Promise(async(res, rej) => {
const inst = new TestService();
await inst.ngOnInit();
res(inst);
});
}
export let testProvider =
{
provide: TestService,
useFactory: testFactory,
deps: []
};