简体   繁体   English

使用拦截器在角度6中对授权请求进行错误处理

[英]Error handling for authorized request in angular 6 using interceptor

I am appending authorization header using interceptor. 我使用拦截器附加授权标头。 Now in interceptor I am also checking only for http error related to 401 ie bad credentials which means the case when valid access token doensnot exist in the sever to access the resource. 现在在拦截器中我也只检查与401相关的http错误,即错误凭证,这意味着当服务器中不存在有效访问令牌以访问资源时的情况。 So if I get 401 error I am logging user out and redirecting to login page. 因此,如果我收到401错误,我将用户注销并重定向到登录页面。 Now for any other server related error I am catching in error block of service call inside component, and displaying appropriate message on UI. 现在,对于任何其他服务器相关的错误,我在组件内的服务调用的错误块中捕获,并在UI上显示适当的消息。 But it seems there is some problem when I logout the user via interceptor. 但是当我通过拦截器注销用户时似乎存在一些问题。 The logout and redirect works fine but the screen goes unresponsive they way it becomes in case of javascript alert message. 注销和重定向工作正常,但屏幕没有响应,因为它变成了javascript警告消息。

component.ts : component.ts:

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

Service.ts Service.ts

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

interceptor.ts: 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);
          }
        }));
      }
  }

you can try like this. 你可以这样试试。 here we are using a interceptor 这里我们使用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      
   }         
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM