bena
bena

Reputation: 45

NullInjectorError: No provider for ConfigService (HttpClient)

I always get an NullInjectorError: R3InjectorError(AppModule)[ConfigService -> ConfigService -> ConfigService]: NullInjectorError: No provider for ConfigService! when creating an instance of the ConfigService.

I did everything the same as in the Angular HttpClient Tutorial (also adding the HttpClientModule to the AppModule), but when injecting the ConfigService in my ConfigComponent it fails:

export class ConfigComponent implements OnInit {
  constructor(private configService: ConfigService){}
...

The ConfigService looks like this:
import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class ConfigService {

  configUrl = 'assets/config.json';

  constructor(private http: HttpClient) {}

  getTest(): Observable<HttpResponse<string>> {
    return this.http.get<string>(this.configUrl, {observe: "response"})
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // Return an observable with a user-facing error message.
    return throwError(
      'Something bad happened; please try again later.');
  }
}

Upvotes: 1

Views: 3959

Answers (1)

Emilien
Emilien

Reputation: 2759

You must specify to Angular that this service should be created by the root application injector. See Angular Dependency Injection.

So just replace

@Injectable()

With

@Injectable({
  providedIn: 'root'
})

Upvotes: 6

Related Questions