I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it:
@NgModule({
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: configFactory,
deps: [ConfigService],
multi: true
},
{
provide: UserService,
useFactory: userServiceFactory,
deps: [
ConfigService
],
multi: true
},
],
bootstrap: [AppComponent]
})
export class AppModule { }
The configFactory function returns a Promise:
export function configFactory(configService: ConfigService): () => Promise<any> {
return (): Promise<any> => {
return new Promise(resolve => {
Device.getInfo().then(info => {
configService.platform = info.platform; // can be either 'ios' or 'web'
});
});
}
}
The value of configService.platform is crucial for deciding the type of UserService provider to use, hence the need for the userServiceFactory method:
const userServiceFactory = (configService: ConfigService): any=> {
if(configService.platform === 'ios') {
return new UserServiceDevice()
} else {
return new UserWebServiceWeb();
}
}
Although the config service initialization works correctly, the userServiceFactory function runs before the configFactory function has finished executing, resulting in config.platform being undefined. It seems like it does not wait for the configFactory function to resolve despite ConfigService being set as a dependency. How can I address this? Are there better approaches to handle such scenarios?