Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a http service in Angular 17 with standalone components

I have a component (see: it is a standalone one):

@Component({
  standalone: true, // <--- See here 
  selector: "app-login",
  imports: [FormsModule, CommonModule],
  templateUrl: "./login.component.html",
  styleUrl: "./login.component.css"
})
export class LoginComponent {
  constructor(private authService: AuthService) {}
}

And the service is (see, it requires HttpClient to be injected):

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export default class AuthService {
  constructor(private http: HttpClient) {} // <--- See here: if I remove this httpClient, it works.
}

It does not works:

ERROR NullInjectorError: R3InjectorError(Standalone[e])[e -> e -> e -> e]: 
  NullInjectorError: No provider for e!

If I remove the httpClient from the constructor of the service, it works (but it does nothing). It seem to me that the injection of the HttpClient inside the service is not working.

Any clue?

Version: Angular 17

PS: lot's of details removed :-)

like image 257
jehon Avatar asked Nov 06 '25 06:11

jehon


2 Answers

Did you provide HttpClient in your app.config.ts like this :

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideAnimations(), provideHttpClient()]
};
like image 163
Q.Rey Avatar answered Nov 08 '25 23:11

Q.Rey


in appConfig you need http client provider

export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()]
};
like image 21
salhi mustapha Avatar answered Nov 08 '25 23:11

salhi mustapha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!