创建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){}
...
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.');
}
}
答案 0 :(得分:0)
您必须向Angular指定该服务应由根应用程序注入程序创建。参见Angular Dependency Injection。
所以只需替换
@Injectable()
使用
@Injectable({
providedIn: 'root'
})