EN VI

Using a http service in Angular 17 with standalone components?

2024-03-12 21:00:04
How to 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 :-)

Solution:

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

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideAnimations(), provideHttpClient()]
};
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login