Reputation: 73
I am trying to build an error interceptor in my angular app. I imported the auth service into it through the constructor. But I am getting an error when I call a method from it that it does not exist. This is the interceptor.
import {Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import {Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor{
constructor(
private authService: AuthService,
){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
return next.handle(req).pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if(error.status === 401){
this.authService.logout();
}
return throwError(error);
}
}
And this is my auth-service.
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AuthService {
url = 'http://localhost:3000/users/login'
isLoggedIn = false;
constructor(private http: HttpClient) { }
redirectUrl: string;
login(credentials): Observable<any> {
return this.http.post<any>(this.url, credentials).pipe(catchError(err => {
return throwError(err);
}));
}
logout(): void {
localStorage.removeItem('token');
this.isLoggedIn = false;
}
getAuthToken(): string{
return localStorage.getItem('token');
}
}
After I try to run it, I get TypeError: Cannot read property 'logout' of undefined
Upvotes: 0
Views: 4173
Reputation: 325
there is an answer to this question here but it was difficult to find.
When providing dependencies to inject into your Interceptors, you need to declare them under the deps
key in the same object that defined your Interceptor in your Module. The following is an example:
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
deps: [AuthService]
},
Hope this helps
Upvotes: 1
Reputation: 31125
You need to use arrow function notation to denote the class using this
keyword in callbacks. Try the following
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
return next.handle(req).pipe(
catchError((error) => this.handleError(error)) // <-- use arrow function here
);
}
Upvotes: 2