angularangular17

Angular Subscribe with API service does not work correctly


I am trying to connect to an API through a service that I have created with Angular but when I enter the page, console browser returns the following error:

main.ts:5 ERROR NullInjectorError: R3InjectorError(Standalone[_HomeComponent])[_EventosService -> _EventosService -> _EventosService -> _HttpClient -> _HttpClient]: 
  NullInjectorError: No provider for _HttpClient!
    at NullInjector.get (core.mjs:1654:27)
    at R3Injector.get (core.mjs:3093:33)
    at R3Injector.get (core.mjs:3093:33)
    at injectInjectorOnly (core.mjs:1100:40)
    at Module.ɵɵinject (core.mjs:1106:42)
    at Object.EventosService_Factory [as factory] (eventos.service.ts:8:28)
    at core.mjs:3219:47
    at runInInjectorProfilerContext (core.mjs:866:9)
    at R3Injector.hydrate (core.mjs:3218:21)
    at R3Injector.get (core.mjs:3082:33)

I am using Angular version 17 in my project and doing the imports in the same HomeComponent component. The affected files are the following.

home.component.ts

import { Component, OnInit } from '@angular/core';
import { EventosService } from '../../shared/services/eventos/eventos.service';
import { Observable } from 'rxjs';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'app-home',
  standalone: true,
  templateUrl: './home.component.html',
  imports: [CommonModule, HttpClientModule],
  styleUrls: ['./home.component.sass']
})

export class HomeComponent implements OnInit{

  constructor( private es: EventosService ) {}

  usuarios : any = {};
  
  ngOnInit(): void {
    this.es.getEventos().subscribe(data => {
      this.usuarios = data;
    });
    console.log(this.usuarios);
  }

}

eventos.services.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable(
  {providedIn: 'root'}
)
export class EventosService {

  private baseUrl = "https://localhost:7019/api";

  constructor( private http: HttpClient ) { }

  public getEventos(): Observable<any> {
    return this.http.get(`${this.baseUrl}/Usuarios`);
  }

}

WARNING: I am aware that the service is called "Eventos" and I am calling "Usuarios" in the API, it is to test that it returns me some result even if it is by console.

INFO I am using Angular 17 with the default settings although the project is migrated from Angular 16. The API is made with .NET but with other tools I can connect well to it and launch requests that return results.


Solution

  • You must add provideHttpClient() from @angular/common/http inside your app.config.ts providers. Then remove the H1ttpClientModule from your component.