angularionic-frameworkhttpclientionic6

Nullinjectorerror: no provider for httpclient! without app.module.ts


I'm trying to read a JSON in Ionic Angular with HttpClient, but I get this error "nullinjectorerror: no provider for httpclient!".

The issue is that the lastest version of angular doesn't generate app.module.ts.

My code:

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

import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs';

@Component({
  selector: 'app-ficha-evento',
  templateUrl: './ficha-evento.page.html',
  styleUrls: ['./ficha-evento.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class FichaEventoPage implements OnInit {

  event:any=[];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getEvnt().subscribe(res=>{
      /*console.log("res",res);*/
      this.event=res;
    });
  }
  
  getEvnt(){
    return this.http
    .get('assets/eventos.json')
    .pipe(
      map((res:any)=>{
        return res.data;
      })
    )
  }

}

Any idea? thanks!!

I'm trying to import HttpClientModule in the page.module.ts, but it doesn't work. I also tried to generate appModule manually... doesn't work either.

Now I'm looking for other ways to acces Json files...


Solution

  • To provide HttpClient in standalone app we could do

    main.ts

    import {provideHttpClient} from '@angular/common/http';
    
    bootstrapApplication(AppComponent, {
      providers: [provideHttpClient()]
    })