Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular How to inject HttpClient in an Angular Service

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading