NullInjectorError:没有提供ConfigService的提供程序(HttpClient)

时间:2020-07-22 08:48:19

标签: angular typescript

创建ConfigService实例时,我总是得到NullInjectorError: R3InjectorError(AppModule)[ConfigService -> ConfigService -> ConfigService]: NullInjectorError: No provider for ConfigService!

我所做的一切与Angular HttpClient Tutorial中相同(也将HttpClientModule添加到AppModule中),但是当将ConfigService注入我的ConfigComponent它失败了:

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

ConfigService如下所示:
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.');
  }
}

1 个答案:

答案 0 :(得分:0)

您必须向Angular指定该服务应由根应用程序注入程序创建。参见Angular Dependency Injection

所以只需替换

@Injectable()

使用

@Injectable({
  providedIn: 'root'
})