Angular 7 给出 this.interceptor is undefined 错误
Angular 7 gives this.interceptor is undefined error
我试图在 angular7 中实现一个 HTTP 拦截器,但它给出了 "this.interceptor is undefined" 错误。这是什么原因?
auth.service.ts - 我在哪里进行 http 调用
@Injectable()
export class AuthService{
constructor(private httpClient: HttpClient){}
login(userName, password){
return this.httpClient.post('/authenticate', {"username" : userName, "password" : password});
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
],
providers: [AuthService, fakeBackendProvider],
bootstrap: [AppComponent]
})
export class AppModule { }
拦截器
import { HTTP_INTERCEPTORS, HttpInterceptor, HttpHandler, HttpEvent} from '@angular/common/http';
class FakeBackendInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { url, method, headers, body } = request;
return next.handle(request);
}
}
export const fakeBackendProvider = {
provide: HTTP_INTERCEPTORS,
useFactory: FakeBackendInterceptor,
multi: true
}
这是我得到的错误,
需要在模块中以不同方式提供拦截器:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendProvider,
multi: true
}
]
确保从 @angular/common/http
导入 HTTP_INTERCEPTORS
。有关拦截器以及如何 提供 拦截器的更多信息,请参阅 docs.
我试图在 angular7 中实现一个 HTTP 拦截器,但它给出了 "this.interceptor is undefined" 错误。这是什么原因?
auth.service.ts - 我在哪里进行 http 调用
@Injectable()
export class AuthService{
constructor(private httpClient: HttpClient){}
login(userName, password){
return this.httpClient.post('/authenticate', {"username" : userName, "password" : password});
}
}
app.module.ts
@NgModule({
declarations: [
AppComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
],
providers: [AuthService, fakeBackendProvider],
bootstrap: [AppComponent]
})
export class AppModule { }
拦截器
import { HTTP_INTERCEPTORS, HttpInterceptor, HttpHandler, HttpEvent} from '@angular/common/http';
class FakeBackendInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { url, method, headers, body } = request;
return next.handle(request);
}
}
export const fakeBackendProvider = {
provide: HTTP_INTERCEPTORS,
useFactory: FakeBackendInterceptor,
multi: true
}
这是我得到的错误,
需要在模块中以不同方式提供拦截器:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendProvider,
multi: true
}
]
确保从 @angular/common/http
导入 HTTP_INTERCEPTORS
。有关拦截器以及如何 提供 拦截器的更多信息,请参阅 docs.