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');
            }
        }
    }
    
    
  • 相关阅读:
    linux下Boost序列化问题解决
    树莓派搭建基于flask的web服务器-通过移动端控制LED
    unison+inotify
    员工为什么会离职 (转)
    编译安装 Centos 7 x64 + tengine.2.0.3 (实测+笔记)
    Cassandra 原理介绍
    使用Go语言编写区块链P2P网络(译)(转)
    缓存击穿举例
    Cassandra 原理介绍
    Go学习之路
  • 原文地址:https://www.cnblogs.com/yuanchao-blog/p/12421397.html
Copyright © 2011-2022 走看看