I am working on an Angular standalone application and encountering the following error when using HttpClient in my DataService:
ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_AuthComponent])[_DataService -> _DataService -> _HttpClient -> _HttpClient]: NullInjectorError: No provider for _HttpClient!
What I Have Done: Environment Details:
Angular Version: 19.0.4 Node.js Version: v20.18.1 TypeScript Version: 5.6.3
Relevant Code:
data.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
constructor(private http: HttpClient) {}
getTransactions(): Observable<any> {
return this.http.get('/api/transactions');
}
}
auth.component.ts:
import { Component } from '@angular/core';
import { DataService } from '../../services/data.service';
import { HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss'],
standalone: true,
imports: [CommonModule, HttpClientModule, FormsModule],
})
export class AuthComponent {
username = '';
password = '';
message: string | null = null;
constructor(private dataService: DataService) {}
login() {
this.dataService
.getTransactions()
.subscribe(data => console.log('Transactions:', data));
}
}
What I Have Tried:
Still Observed Behavior: Despite these efforts, the application fails to resolve HttpClient and continues to throw the error.
My Question:
Any help or insights are greatly appreciated. Thanks in advance!
I found the soltion myself.
No need to inject into individual components.
Two things must be done.
app.config.ts
add followingimport { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {providers[provideHttpClient(withFetch())]
appConfig
into bootstaping part at main.ts
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, {
...appConfig,
}).catch((err) => console.error(err));