Angular (v5) service is getting constructed before APP_INITIALIZER promise resolves
I had also a simmilar issue what solved the issue for me was to use Observable methods and operators to do everything. Then in the end just use the toPromise
method of the Observable
to return a Promise
. This is also simpler because you don't need to create a promise yourself.
The AppConfig
service will then look something like that:
import { Injectable, Injector } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Observable } from 'rxjs/Observable';import { tap } from 'rxjs/operators/tap';@Injectable()export class AppConfig { config: any = null; constructor( private injector: Injector ){ } public loadConfig() { const http = this.injector.get(HttpClient); return http.get('https://jsonplaceholder.typicode.com/posts/1').pipe( tap((returnedConfig) => this.config = returnedConfig) ).toPromise(); //return from([1]).toPromise(); }}
I'm using the new pipeable operators in rxjs which is recommended by Google for Angular 5. The tap
operator is equivalent to the old do
operator.
I have also created a working sample on stackblitz.com so you can se it working. Sample link
async loadConfig() { const http = this.injector.get(HttpClient); const configData = await http.get('http://mycoolapp.com/env') .map((res: Response) => { return res.json(); }).catch((err: any) => { return Observable.throw(err); }).toPromise(); this.config = configData; }); }
The await operator is used to wait for a Promise. It can only be used inside an async function.
It is working fine.
Injector does not wait for observables or promises and there is no code that could make it happen.
You should use custom Guard or Resolver to ensure that config is loaded before initial navigation completes.