🏹 Using APP_INITIALIZER in Angular

Tacettin Sertkaya
2 min readDec 22, 2023

--

What’s APP_INITIALIZER?

The APP_INITIALIZER is a well-defined instance of the InjectionToken. It is a built-in Injection token that is thoughtfully provided by Angular.

Angular executes the function associated with a token during application loading. If the function returns a promise, Angular will wait for the promise to resolve before initializing the application. This makes it an ideal location to execute initialization logic.

We may keep important data like URLs, and themes, or adding dynamic routes, etc in the project. APP_INITIALIZER is used to fetch configuration data before the application starts. This ensures that the application has all the necessary configurations in advance.

Let’s Make a Sample

We would add dynamic routes depending on whether the user is authenticated or unauthenticated

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

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { AuthService } from './services/auth.service';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { LandingComponent } from './pages/landing/landing.component';

export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes), provideClientHydration(),
{
provide: APP_INITIALIZER,
useFactory: initializeAppDynamicRouting,
multi: true,
deps: [Router, AuthService],
},
]
};



export function initializeAppDynamicRouting(
router: Router,
authService: AuthService,
): () => Promise<void> {



return () =>
new Promise((resolve) => {

if (authService.isAuthenticated()) {

router.resetConfig([
...routes,
{
path: 'dashboard',
component: DashboardComponent,
},
]);
}
else {
router.resetConfig([
...routes,
{
path: 'landing',
component: LandingComponent,
},
]);
}


setTimeout(() => {
console.log(
'initializeAppDynamicRouting: router.config',
router.config,
);
resolve();
}, 2000);
});
}

  • While the app is initializing, the page appears to be blank. We are waiting for the APP_INITIALIZER function to complete its tasks before the app can fully load. After 2 seconds dynamic routes have been added.

Conclusion

Learn how to dynamically change routes and use APP_INITIALIZER. Also, you will find regarding code below the repo link.

GitHub Link: https://github.com/tacettinsertkaya/APP_INITIALIZER_Samples

--

--