[Fixed] Nullinjectorerror: no provider for httpclient! without app.module.ts – Httpclient

by
Ali Hasan
angular angular-httpclient ionic-framework ionic6

The Problem:

When attempting to utilize HttpClient in an Ionic Angular application without an app.module.ts file, a "nullinjectorerror: no provider for httpclient!" error occurs. The issue arises due to the latest version of Angular no longer automatically generating an app.module.ts file, which is necessary for providing the HttpClient service. The code snippet provided attempts to import HttpClient without the appropriate module declaration, resulting in the error message. The user has tried importing HttpClientModule in the page.module.ts file but it does not resolve the issue, and they are seeking alternative methods to access JSON files.

The Solutions:

Solution 1: Importing HttpClientModule in Main.ts

To resolve the "nullinjectorerror: no provider for HttpClient!" error in standalone Angular applications, we can manually provide the HttpClient module in the main.ts file.

In main.ts:

import {provideHttpClient} from '@angular/common/http';

// Provide the HttpClient module
bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()]
});

By doing this, we explicitly provide the HttpClient service in the application’s root injector, making it accessible to all components in the application.

Solution 2: Adding App Config File

In Angular 17, with the standalone option enabled, an app.config.ts file is generated in src/app/. This file can be used to add providers, such as HttpClientProvider, to resolve the “No Provider for HttpClient” error. Here’s the updated app.config.ts:

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

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClientHydration(),
    provideHttpClient(),
  ],
};

By including provideHttpClient() in the providers array, the HttpClient service will be available for injection in your components and services.

Solution 3: {title}

This solution suggests using a service class to call the HTTP request instead of directly importing HttpClientModule in the page module. Here’s how it’s done:

component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';

@Component({
  selector: 'app-ficha-evento',
  templateUrl: './ficha-evento.page.html',
  styleUrls: ['./ficha-evento.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule],
})
export class FichaEventoPage {
  events$ = this.eventService.getEvents();

  constructor(private eventService: EventService) {}
}

component.html

<div>{{ events$ | async }}</div>

<!-- for seeing object content (For debugging) -->
<pre>{{ events$ | async | json }}</pre>

event.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, take } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EventService {
  constructor(private http: HttpClient) {}

  getEvents() {
    return this.http
      .get('/assets/eventos.json')
      .pipe(
        take(1),
        map((res: any) => {
          return res.data;
        })
      );
  }
}

This way, the HttpClientModule is only imported at the root level, and a service is used to make the request.

Q&A

What is the error message?

Nullinjectorerror: no provider for httpclient!

What is the cause of the error?

The error is due to the absence of app.module.ts in the latest version of angular.

Video Explanation:

The following video, titled "”[Debugging", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video provides further insights and detailed explanations related to the content discussed in the article.

NullInjectorError: No provider for {Class}! – YouTube” description=”… | Angular Error. Code With Yousaf•1.6K views · 9:38. Go to channel · error: staticinjectorerror(dynamictestmodule)[httpclient]:. DotNet Techy …”]