I am trying to set up a runtime configuration value for a URL in my angular project how it is outlined in this thread, and I can’t seem to figure out why i am getting a NullInjectorError: NullInjectorError: No provider for _HttpClient! When to me i think i am adding the module correctly.
This is my app-config.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private appConfig: any;
constructor(private http: HttpClient) {
console.log("HttpClient is injected:", http);
}
loadAppConfig(): Promise<void>{
return this.http.get('/assets/config.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
// This is an example property ... you can make it however you want.
get apiBaseUrl() {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig.apiBaseUrl;
}
}
and this is my app.component.ts
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './app-config.service';
import { HttpClientModule } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterModule,
MatIconModule,
HttpClientModule],
template: `
<main>
<a [routerLink]="['/']">
<header class="brand-name">
<!-- <mat-icon aria-hidden="false" aria-label="Example home icon" fontIcon="home"></mat-icon> -->
<button mat-button class="home-button">
<mat-icon aria-hidden="false" aria-label="Example home icon" fontIcon="home"></mat-icon>
Home
</button>
</header>
</a>
<section class="content">
<router-outlet></router-outlet>
</section>
</main>
`,
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [AppConfigService],
useFactory: (appConfigService: AppConfigService) => {
return () => {
//Make sure to return a promise!
return appConfigService.loadAppConfig();
};
}
}
],
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'draft-tool';
textInput: string = '';
}
I dont know if it is my router link taking me to a different component, but i tried adding the client module the same way in that file as i did in my app.component.ts and it didnt seem to help at all.
I think i may just be missing something fundamentally in how this is working in angular, this is just a side project i’m taking on to learn front end as I have only been a backend dev for years.
I am expecting to be able to load a URL in at runtime so i can change the value when I am doing development, and when I am deployed to my AWS env.