#Angular 18 - provider undefined

5 messages · Page 1 of 1 (latest)

scarlet steppe
#

I am trying to use APP_INITIALIZER wanted to use a dependency. I read in the official docs that is to add the deps property the object that we are going to use, and then we can use it at the useValue property as a parameter function (cmiiw).

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    SomeService,
    {
      provide: APP_INITIALIZER,
      useValue: (someService: SomeService) => someService.test(),
      deps: [SomeService],
      multi: true,
    },
  ],
};

Here's the service that is imported:

@Injectable({ providedIn: 'root' })
export class SomeService {
  test() {
    console.log('okay');
  }
}

Tho why does it still gives me an error saying that the object is undefined?

#

I also tried to use useFactory to replace useValue tho it didnt do anything different. the error still persisted

mint brook
scarlet steppe
#

ah I see, so it must be useFactory with functions + functions.

another way I also find out after trying out things is:

import {
  APP_INITIALIZER,
  ApplicationConfig,
  inject,
  provideZoneChangeDetection,
} from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { SomeService } from './some/some.service';
export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    {
      provide: APP_INITIALIZER,
      useFactory: () => {
        const someService = inject(SomeService);
        return () => someService.test();
      },
      multi: true,
    },
  ],
};

tho idk if its a better approach or not (or just the same performance wise?)

mint brook
#

Yeah this is a more modern approach, and I don't think there is any difference