I'm creating a standalone app from scratch, I don't have an ngModule.
I'm creating a translation service, and a pipe to use it.
testing it on app.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { I18nPipe } from './pipes/i18n.pipe';
import { I18nService } from './services/i18n.service';
@Component({
selector: 'ct-v4',
standalone: true,
imports: [CommonModule, RouterOutlet, I18nPipe],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'ct-v4';
constructor(private i18nService: I18nService) {}
ngOnInit(): void {
this.i18nService.initLanguage('en');
}
}
My i18n service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class I18nService {
private translations: { [key: string]: string } = {};
constructor(private http: HttpClient) {}
initLanguage(lang: string, isFallback = false): void {
this.http.get(`/langs/${lang}.json`).subscribe({
next: (data: any) => {
this.translations = data;
},
error: (error) => {
console.error(`Language file for ${lang} not found.`);
if (!isFallback) {
console.info('Falling back to default language: en');
this.initLanguage('en', true);
} else {
console.error('Even the default language "en" is missing. Stopping language initialization.');
}
}
});
}
i18n(key: string): string {
return this.translations[key] || key;
}
}
The pipe itself is not complaining because it's also standalone, I get this error:
NullInjectorError: R3InjectorError(Standalone[AppComponent])[I18nService -> I18nService -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
I'm not finding examples online on how to use services in standalone angular apps
Any ideas?
You are using HttpClient
service but you don't provide the HTTP client. To fix it, go to your app.config.ts
and add provideHttpClient()
to the providers
:
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
}
In case you don't have an app.config.ts
, go to your main.ts
and add the following where your app is bootstrapped:
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
],
});
For more information, see the dependency injection guide.