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
You need to add
provideHttpClient()
from@angular/common/http
to theproviders
ofAppConfig
(or directly tobootstrapApplication(AppComponent, {providers: [...]})
)should fix your problem