I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to these services as Initialization, Config, and UserDetails. To facilitate this, I have included these services in the app-module.ts file as shown below.
`
export function initializeApp(initService: InitializationService) {
return () => initService.getInit();
}
export function fetchSettings(configService: ConfigService) {
return () => configService.getConfig();
}
export function retrieveUserSettings(userDetails: UserDetailsService) {
return () => userDetails.getSettings();
}
@NgModule({
imports: [/*my-imports*/],
providers: [
AppLoadService,
{ provide: APP_INITIALIZER, useFactory: initializeApp, deps: [InitializationService], multi: true },
{ provide: APP_INITIALIZER, useFactory: fetchSettings, deps: [ConfigService], multi: true },
{ provide: APP_INITIALIZER, useFactory: retrieveUserSettings, deps: [UserDetailsService], multi: true }
]
})
` The InitializationService contains values necessary for the proper functioning of the other two services. The service requests are sent immediately during app initialization. I require the ConfigService and UserDetailsService to be invoked only after the InitializationService call is completed. To address this, I have implemented the following,
// AppConfig.ts
export class AppConfig {
public static Config= {};
public static $subject = new Subject();
}
// InitializationService
getInit () {
const promise = new Promise((resolve, reject) => {
this.http.get().then(val => {
AppConfig.config = val;
AppConfig.$subject.next(val);
});
};
return promise;
}
//ConfigService
getConfig () {
if(AppConfig.Config.baseUrl === undefined) {
AppConfig.$subject.subscribe(val => {
this.http.get(AppConfig.Config.baseUrl).then(//doSomething);
})
}
}
A static subject is created and subscribed to in order to coordinate the sequence of calls. Once the InitializationService completes, it emits the next value for the subject, which is then observed by the ConfigService. Upon receiving the subscribed call, further operations are carried out. The same implementation is duplicated for the UserDetails getSettings() method.
Is my approach correct? Have you experimented with any other proven patterns?
Any suggestions or better approaches to handle the above scenario would be greatly appreciated.
Thank you in advance.
Best regards, hawx