skip to Main Content

I want a service which uses http requests.

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

@Injectable({
  providedIn: 'root',
})

export class BackendService {
  private backendUrl = 'http://localhost:4200/';

  constructor(private http: HttpClient) { }

  //not done as observable
  uploadImage(image: any) {
    let formData = new FormData()
    formData.append("image",image);

    return this.http.post<any>(`${this.backendUrl}/upload`, formData);
  }
}

and a component in which i want to inject it:

import { BackendService } from '../backend-service.service';

@Component({
  selector: 'app-image-picker',
  standalone: true,
  imports: [MatCardModule,CommonModule,MatButtonModule,MatIconModule],
  templateUrl: './image-picker.component.html',
  styleUrl: './image-picker.component.css'
})
export class ImagePickerComponent {
  selectedImage: string | ArrayBuffer | null | undefined = null;

  constructor(private backendService: BackendService){}
}

This however throws me aNullInjectorError: No provider for _HttpClient! Error.

In the tutorial they appear to add the services to the app.module.ts. However I dont have an app.module.ts and the current way to is to use standalone components.

How can i resolve this? Do i need to create the app.module.ts or is there a better way?

2

Answers


  1. You need to add provideHttpClient() from @angular/common/http to the providers of AppConfig (or directly to bootstrapApplication(AppComponent, {providers: [...]}))

    Login or Signup to reply.
  2. import { ApplicationConfig } from '@angular/core';
    import { provideRouter } from '@angular/router';
    
    import { routes } from './app.routes';
    import { provideHttpClient } from '@angular/common/http';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideRouter(routes),
        provideHttpClient()
      ]
    };
    

    should fix your problem

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