使用拦截器处理角度6中授权请求的错误

时间:2019-06-18 12:28:46

标签: angular angular6 rxjs6

我正在使用拦截器附加授权标头。现在在拦截器中,我还只检查与401相关的http错误,即凭据错误,这意味着在服务器上不存在有效的访问令牌时无法访问资源的情况。因此,如果出现401错误,我正在注销用户并重定向到登录页面。现在,对于任何其他服务器相关的错误,我都陷入了组件内部服务调用的错误块,并在UI上显示了适当的消息。但是当我通过拦截器注销用户时,似乎存在一些问题。注销和重定向可以正常工作,但是在出现JavaScript警报消息的情况下,屏幕无法响应,因此变得无响应。

component.ts:

 this.Servicefunction(arg).subscribe((Response: any) => {
        //somthing/
        }, (err: any) => {
            alert("Server error occured");
        });

Service.ts

Servicefunction(arg): Observable<any> {
    let body = { "arg": arg }
    return this.httpClient.post("http://xx.xx.xx:xx/CheckExistenceOfRecord', body);
}

interceptor.ts:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpHeaders, HttpParams, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { Observable } from 'node_modules/rxjs';
import { CookieService } from 'ngx-cookie-service';
import { ActivatedRoute, Router } from '@angular/router';
import { AppComponent } from './app.component';
import { AuthService } from './route-auth';
import { map, catchError, filter, switchMap } from 'rxjs/operators'

@Injectable()
export class Interceptor implements HttpInterceptor {
  constructor(private cookieService: CookieService, private route: Router, private appComp: AppComponent,  private authService: AuthService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token: string = this.cookieService.get('authToken');
        const headers = new HttpHeaders().append('Authorization', token).append('Content-Type', 'application/json');
        const AuthRequest = request.clone({ headers: headers });
        return next.handle(AuthRequest).pipe(catchError((err: any, caught) => {
          if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
              console.info('err.error =', err.error, ';');
              this.authService.logout();
              this.route.navigateByUrl('');
              this.cookieService.deleteAll('/');
            }
            return Observable.throw(err);
          }
        }));
      }
  }

1 个答案:

答案 0 :(得分:0)

您可以尝试这样。这里我们使用的是interceptor

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

  private handleError(error: HttpErrorResponse): Observable<any> {
     if (error.status === 401) {
      // Do your thing here      
   }         
  }