I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER
:
{
provide: APP_INITIALIZER,
useFactory: initializeSettings,
deps: [SettingsService],
multi: true
}
export function initializeSettings(config: SettingsService) {
return () => config.loadOne();
}
//import declarations
@Injectable()
export class SettingsService {
constructor(private http: HttpClient) { }
loadOne(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
this.http.get('url').subscribe(value => {
console.log('loadSettings FINISH');
resolve(true);
});
});
}
loadTwo(): Observable<any> {
const promise = this.http.get('url');
promise.subscribe(value => {
console.log('loadSettings FINISH');
});
return promise;
}
}
In my application, there is a function called manageSettings()
that requires the data from the SettingsService
service be initialized.
When utilizing the loadTwo()
function, the app does not wait for it to complete:
app-root constructor
manageSettings()
loadSettings FINISH
However, when using the loadOne()
function, everything works as expected:
loadSettings FINISH
app-root constructor
manageSettings()
It's puzzling why this discrepancy occurs. Can someone shed some light on this situation?