Creating a Standalone Self Initializing Angular Asset Service

Ole Ersoy
1 min readMay 26, 2023

--

Image by PublicDomainPictures from Pixabay

Scenario

We have an asset service that loads SVG assets for us and makes them available in the MatIconRegistry .

In the pre Angular 15 version of the service the initialization was done in the service module’sconstructor .

constructor(private a: AssetService) {
a.init()
}

The writeup for the first version is here.

Here’s the full demo pre Angular 15 demo.

We want to convert this to a standalone service.

Approach

We will use the multi-token ENVIRONMENT_INITIALIZER allowing us register code that gets executed as the application boots. Also note that we are including provideHttpClient() since the MatIconRegistry uses this to fetch the SVG asset via the provided URL.

bootstrapApplication(App, {
providers: [
provideHttpClient(),
{
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useValue: () => inject(AssetService).init(),
},
],
});

Demo

--

--