Reputation: 1438
I'm trying to implement a HTTP Interceptor in angular7, but it gives "this.interceptor is undefined" error. What is the reason for it?
auth.service.ts - where i make http call
@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 { }
interceptor
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
}
This is the error i get,
Upvotes: 1
Views: 1260
Reputation: 15423
Interceptors need to be provided differently in the module:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: FakeBackendProvider,
multi: true
}
]
Make sure to import HTTP_INTERCEPTORS
from @angular/common/http
. More info on interceptors and how to provide them can be found in the docs.
Upvotes: 2