zoukankan      html  css  js  c++  java
  • 关于Angular2请求拦截器

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { MessagesService } from 'app/shared/service';
    import { HttpInterceptor, HttpRequest, HttpHandler, HttpHeaders, HttpEvent, HttpErrorResponse, HttpResponse } from '@angular/common/http';
    import { catchError, map } from 'rxjs/operators';
    import { LoginService } from 'app/auth/login.service';
    
    @Injectable()
    export class RequestInterceptor implements HttpInterceptor {
        constructor(private msg: MessagesService, private ls: LoginService) {}
    
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any> | any> {
            let _headers = new HttpHeaders()
                .set('Authorization', this.ls.getAccessToken() + '')
                // .set('X-Requested-With', 'XMLHttpRequest')
                // .set('Content-Type', 'application/json')
                .set('Accept', '*/*')
                .set('token', `${localStorage.getItem('token')}`)
                .set('roleId', `${localStorage.getItem('role_id')}`)
                .set('userId', `${localStorage.getItem('user_id')}`)
                .set('tenantId', `${localStorage.getItem('tenant_id')}`);
                // .set('userName', localStorage.getItem('user_name') || '');
    
            const body = req.body;
            const isFormData = body instanceof FormData;
    
            req.headers.keys().forEach(item => {
                _headers = _headers.set(item, req.headers.get(item));
            });
    
            const authReq = req.clone({
                headers: _headers
            });
            // 针对导入文件为post请求body参数为FormData类型的接口
            const importreq = req.clone({
                headers: _headers
            });
            console.log(authReq);
            // console.log(importreq);
    
            return next.handle(isFormData ? importreq : authReq).pipe(
                 // 对所有接口进行登陆超时拦截,跳转登陆页面
                // map((event: any) => {
                //     if (event instanceof HttpResponse) {
                //       if (event.body && event.body.code === 300) {
                //         this.ls.logIn();
                //       } else {
                //           return event;
                //       }
                //     }
                // }),
                catchError((err: HttpErrorResponse) => {
                    this.handleError(err.status);
                    throw err;
                })
            );
        }
    
        // 报错信息
        handleError(status) {
            if (status === 0) {
                this.msg.error(`${status} please checkout the network`);
            } else if (status === 401) {
                // this.msg.error(`user token out of date`);
                // this.ls.logOut();
            } else if (status === 404) {
                this.msg.error('The requested resource does not exist');
            } else if (status === 500) {
                this.msg.error('server error, please try again later');
            } else {
                // this.msg.error('未知错误,请检查网络');
                console.error('an unknown error');
            }
        }
    }
    
    
  • 相关阅读:
    Code review
    一点心得
    有关双向追踪性的一点感觉
    测试用例分析的一点心得
    js简单的抽屉菜单
    新的感受
    linux的VPS如何分区
    PHP中Unicode转码和解码的实现
    xampp安装及配置
    js Unicode编码转换
  • 原文地址:https://www.cnblogs.com/yuanchao-blog/p/12421397.html
Copyright © 2011-2022 走看看