#How to provide a valye from an async function?

3 messages · Page 1 of 1 (latest)

white sage
#

How to provide a valye from an async function? For example, a fetch result from an URL? I've tried the following:


const TOKEN = new InjectionToken<ConfObject>('confObject');

async function asyncFunction() {
    const resp = await fetch(`<url>`);
    const config = await resp.json() as MyObject;
    return ({a: config.a, b: config.b, c: environment.value} as ConfObject)
}

const ConfObjectFactory = () => {
    return () => asyncFunction();
}

bootstrapApplication(AppComponent, {
    providers: [
        {
            provide: TOKEN,
            useFactory: ConfObjectFacctory()
        },
    ]);

When I do that, inject(TOKEN) returns a ZonedAwarePromise (a promise, anyway...). But other places expect to get injected an instance of ConfObject.

I know I'm missing something, but I can't find what... Any help will be greately appreciated.

grand tusk
#

You can't provide an async value directly. However you can get your config before bootstrap

   asyncFunction()
    .then(config => bootstrapApplication(AppWrapperComponent,
      mergeApplicationConfig({ providers: [{ provide: TOKEN, useValue: config }] }, appConfig)
    ))
    .catch(err => console.error(err));
#

just keep in mind that this will obviously delay the bootstrap process until your config is loaded so depending on how long this api call usually takes, i would add some placeholder/loading stuff in your index.html that gets removed when the bootstrap is done