skip to Main Content

`I am new to angular and I have this error, I have a service using http which I want to be passed to another service to then be used in the component, did some research and it says newer versions of angular don’t use ngmodules anymore so it won’t let me bootstrap the appcomponent

Not sure how to provide Httpmodule to my service
NullInjectorError: No provider for HttpClient!`

**auth service.ts**
export class AuthService {
  private apiUrl = 'https://api.themoviedb.org/3/'; // Replace this with your backend API URL

  constructor(private http: HttpClient) { }

  // Function to handle user login
  login(): Observable<any> {}

//**movieService.ts**
@Injectable({
  providedIn: 'root'
})

export class MovieService {
  apiUrl = 'https://api.themoviedb.org/3/'
  AuthService: AuthService = inject(AuthService);
  

  constructor() {}

2

Answers


  1. You need to call provideHttpClient() in your application config to set the providers used by the HttpClientModule.

    It should look something like following:

    boostrapApplication(AppComponent, { providers: [provideHttpClient()]});
    
    Login or Signup to reply.
  2. In Angular, the HttpClient is part of the HttpClientModule which you need to import in your root module (AppModule usually) to be able to use it.

    Your AuthService uses the HttpClient in its constructor, so you need to make sure that you import the HttpClientModule in your app module like the following.

    File: app.modules.ts

    import { HttpClientModule } from '@angular/common/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppComponent } from './app.component';
    
    
    
    @NgModule({
      declarations: [
        AppComponent,
        // ... other stuff
      ],
      imports: [
        BrowserModule,
        HttpClientModule, // <-- Make sure you import HttpClientModule AFTER BrowerModule!!!
    
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    The HttpClientModule is only imported once, in the root module. Angular’s dependency injection system will then make the HttpClient available evrywehre in your app.

    For your MovieService, you should use Angular’s constructor-based dependency injection.

    import { AuthService } from './auth.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class MovieService {
      apiUrl = 'https://api.themoviedb.org/3/'
    
      constructor(private authService: AuthService) { }
     
    }
    

    Dont forget to replace ‘./auth.service’ with the correct path to your AuthService!!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search