• angular cli http请求封装+拦截器配置+ 接口配置文件


    内容:接口配置文件、http请求封装 、拦截器验证登录

    1、接口配置文件

    app.api.ts

    import { Component, OnInit } from '@angular/core';
    /**
     * 接口配置文件
     * baseurl
     * urlList
     */
    export class apiList implements OnInit {
      baseurl: any = '';
      urlList: any = {};
      constructor() { 
        this.baseurl = 'http://127.0.0.1';
        this.urlList =  {
          'login': {
            path: '/login',
            params: {
              username: '',
              password: ''
            }
          },
          'getUser': {
            path: '/getUser',
            params: {
              id: ''
            }
          }
        }
      }
      ngOnInit() {}
    }

    上面模拟定义了两个接口

    2、http请求封装

    app.service.ts

    import { Component, Injectable } from '@angular/core';
    import { HttpClient, HttpParams } from '@angular/common/http';
    import {apiList} from './app.api';  // 引入api配置文件
    
    @Component({
      providers:[apiList]
    })
    
    @Injectable()
    export class selfHttp {
      public restServer;
      public http;
      status = {
        '0': '请求超时,请检查网络是否断开或者链接是否正确',
        "400": "错误的请求。由于语法错误,该请求无法完成。",
        "401": "未经授权。服务器拒绝响应。",
        "403": "已禁止。服务器拒绝响应。",
        "404": "未找到。无法找到请求的位置。",
        "405": "方法不被允许。使用该位置不支持的请求方法进行了请求。",
        "406": "不可接受。服务器只生成客户端不接受的响应。",
        "407": "需要代理身份验证。客户端必须先使用代理对自身进行身份验证。",
        "408": "请求超时。等待请求的服务器超时。",
        "409": "冲突。由于请求中的冲突,无法完成该请求。",
        "410": "过期。请求页不再可用。",
        "411": "长度必需。未定义“内容长度”。",
        "412": "前提条件不满足。请求中给定的前提条件由服务器评估为 false。",
        "413": "请求实体太大。服务器不会接受请求,因为请求实体太大。",
        "414": "请求 URI 太长。服务器不会接受该请求,因为 URL 太长。",
        "415": "不支持的媒体类型。服务器不会接受该请求,因为媒体类型不受支持。",
        "416": "HTTP 状态代码 {0}",
        "500": "内部服务器错误。",
        "501": "未实现。服务器不识别该请求方法,或者服务器没有能力完成请求。",
        "503": "服务不可用。服务器当前不可用(过载或故障)。"
      };
    
      constructor(Http: HttpClient, public api: apiList) {
        console.log(this.api.baseurl);
        this.http = Http;
        this.restServer = this.api.baseurl;
      }
    
      public get(url, params?: Object, cb?: Function) {
        this.msg(url);
        let httpParams = new HttpParams();
        const vm = this;
        if (params) {
          for (const key in params) {
            if (params[key] === false || params[key]) {
              httpParams = httpParams.set(key, params[key]);
            }
          }
        }
        vm.http.get(vm.restServer + url, { params: httpParams })
          .subscribe(data => {
            cb(data);
          },(err)=>{
            console.log(this.status[err.status]);
          });
      }
    
      public post(url, data?: Object, cb?: Function, options?: Object) {
        this.msg(url);
        const vm = this;
        vm.http.post(vm.restServer + url, data, options)
          .subscribe(res => {
            cb(res);
          }, (err) => {
            console.log(err);
            console.log(this.status[err.status]);
           }, () => {
             //...请求完成
           }
          );
      }
    
      public put(url, data?: Object, cb?: Function, options?: Object) {
        this.msg(url);
        const vm = this;
        vm.http.put(vm.restServer + url, data, options)
          .subscribe(res => {
            cb(res);
          },(err)=>{
            console.log(this.status[err.status]);
          });
      }
    
      public delete(url, params?: Object, cb?: Function) {
        this.msg(url);
        let httpParams = new HttpParams();
        const vm = this;
        if (params) {
          for (const key in params) {
            if (params[key]) {
              httpParams = httpParams.set(key, params[key]);
            }
          }
        }
        vm.http.delete(vm.restServer + url, { params: httpParams })
          .subscribe(data => {
            cb(data);
          },(err)=>{
            console.log(this.status[err.status]);
          });
      }
      public msg(url) {
        console.log('/*')
        console.log(' **开始请求',url)
        console.log(' */')
      }
    }

    上面定义了几个请求的函数,已经提示信息的函数。

    app.module.ts注入

    import {apiList} from './common/app.api';
    .
    .
    ..
    providers: [httpInterceptorProviders, apiList],

    example.ts

    import { Component, OnInit } from '@angular/core';
    import { HttpHeaders } from '@angular/common/http';
    import { selfHttp } from 'src/app/common/app.service';
    import {apiList} from '../common/app.api';  // 引入
    @Component({
      selector: 'app-article',
      templateUrl: './article.component.html',
      styleUrls: ['./article.component.css'],
      providers:[selfHttp, apiList]
    })
    export class ArticleComponent implements OnInit {
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': 'my-auth-token'
        })
      };
      data: any;
      constructor(public http: selfHttp, public api: apiList) {
        console.log(this.api);
      }
    
      ngOnInit() {
        this.http.post(this.api.urlList.login.path, {username: 1, password:22, other:1113}, res => {
          console.log('结果', res);
        }, this.httpOptions);
    
      }
    }

    然后访问的话就会

    2、拦截器

    app.myintercept.ts

    /**
     * 拦截器验证token
     */
    import { Injectable } from '@angular/core';
    import {HttpInterceptor, HttpHandler, HttpRequest, HttpEvent,} from '@angular/common/http';
    import { Router } from '@angular/router';
    import { Observable,  } from 'rxjs';
    import {apiList} from './app.api'
    
    @Injectable()
    export class InterceptorService implements HttpInterceptor {
        
        constructor( public router: Router,  public api: apiList) { 
            // localStorage.setItem('access_token', 'xxxxxxxxxxxxx')
        };
        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            let authReq: any;
            // 实现第一次不拦截的方式:1. 指定接口不拦截  2. 判断本地localStorage
            let loginUrl = this.api.baseurl + this.api.urlList['login']['path'];
            if (req.url !== loginUrl) {
                if (localStorage.getItem('access_token')) {
                    // console.log(2);
                    const token = localStorage.getItem('access_token');
                    authReq = req.clone({ setHeaders: { token } });
                    return next.handle(authReq);
                } else {
                    // 未登录  ==  access_token
                    this.router.navigate(['/login']);
                }
            }
            authReq = req.clone({ setHeaders: {} });
            return next.handle(authReq);
        }
        
    }

    上面请求会验证是否有token,没有就跳转到登录页面。

    定义拦截器收集文件

    http-intercepts/index.ts

    /**
     * 拦截器 收集
     * barrel
     */
    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    import { InterceptorService } from '../app.myIntercept';
    
    export const httpInterceptorProviders = [
        { provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true },
    ];

    app.module.ts注入

    import {httpInterceptorProviders} from 'src/app/common/http-interceptors/index'
    .
    .
    .
    .
    providers: [httpInterceptorProviders, apiList],

    现在如果进入页面请求,没有带token的话就会自动跳转到登录页面。

    github: https://github.com/ft1107949255/BackSystem

  • 相关阅读:
    office 所有后缀对应的 content-type
    Vue 拖拽组件 vuedraggable 和 vue-dragging
    vue实现word,pdf文件的导出功能
    vue浏览器全屏实现
    对于js中事件冒泡的理解分析
    一个服务端的登录拦截
    ES6兼容ie9, flex兼容ie9
    webpack报错
    vue项目的一个package.json
    vue项目的构建过程
  • 原文地址:https://www.cnblogs.com/shuangzikun/p/taotao_angular_cli_intercept.html
Copyright © 2020-2023  润新知