APP_INITIALIZER not resolving promises before continuing to other providers

49 Views Asked by At

I'm struggling to see what I am missing here. Hopefully it's just a small issue.

My problem lies with the APP_INITIALIZER not completely resolving.

I have two services: AppSettingsService and SomethingService. I created a new injectable token "API_BASE_URL" that I want to inject in SomethingService. AppSettingsService has a method called setup() that sets the string "test" in a Promise. I want to finish resolving this promise before continuing on to set API_BASE_URL. However, it doesn't seem to want to wait!

I've attached a sandbox:

Sandbox

Open the console and have a look. It runs as:

"Executing promise" (this is expected) "Getting test string too early" (this I would expect after the promise has resolved) "undefined" (this is because I am printing appSettings.test but it hasn't been set yet because the Promise hasn't completed) "Resolving promise" (this happens shortly after (because of the setTimeout())

Thanks for any help!

1

There are 1 best solutions below

1
Naren Murali On BEST ANSWER

The return statement is missing for all the providers useFactory sections, kindly find below the corrected code!

import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { AppSettingsService } from './app-settings.service';
import { API_BASE_URL } from './something.service';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    AppSettingsService,
    {
      provide: APP_INITIALIZER,
      multi: true,
      deps: [AppSettingsService],
      useFactory: (appSettingsService: AppSettingsService) => {
        return () => {
          return appSettingsService.setup();
        };
      },
    },
    {
      provide: API_BASE_URL,
      deps: [AppSettingsService],
      useFactory: (appSettingsService: AppSettingsService) => {
        console.log('Getting test string too early');
        console.log(appSettingsService.test);
        return appSettingsService.test;
      },
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

code sandbox