错误TypeError:无法读取未定义的属性“导航”

时间:2019-04-17 08:06:48

标签: angular

我正在实现一个Anguar拦截器,以便从服务器返回401错误的任何请求都应导航回登录页面,并且我收到此错误。

ERROR TypeError:无法读取未定义的属性“ navigate”

为什么会出现此错误?

import { Injectable, InjectionToken } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor{

  constructor(private router: Router) { }

      handleError(error: HttpErrorResponse){
        console.log("Error Occured")
        if(error.status == 401){
          console.log("Error Occured 401")        
          this.router.navigate([""]);
        console.log("Logged Out: Session Timeout")
        }
        return throwError(error)
      }

      intercept(req: HttpRequest<any>, next: HttpHandler): 
      Observable<HttpEvent<any>>{
        return next.handle(req)
        .pipe(
          catchError(this.handleError)
        );
      }
}

1 个答案:

答案 0 :(得分:0)

尝试

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                location.reload(true);
            }            
            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
      }
     }

并在服务AuthenticationService中创建重定向登录的方法