angular-cli中axios请求拦截、响应拦截的配置

首先你要确保angular-cli环境搭建成功

 

第一步:

npm 安装axios,文件根目录下安装,指令如下

npm install axios --save  //安装到生产环境

 

第二步:

配置  config.js  文件,它是整个项目的统一配置文件,方便我们管理项目

在angular-cli项目的 src/ 文件夹下新建一个文件夹为 plugins,然后在 plugins/ 下新建 config.js  文件,写入如下代码

// 测试域名
// const testDomin = '' // 使用代理
const testDomin = 'http://172.20.1.26:8082'
// const testDomin = 'http://172.20.1.148:8082'

// 正式域名
const formalDomain = 'http://39.96.91.52/back'

// 环境变量
const env = process.env.NODE_ENV
const origin = env === 'development' ? testDomin : formalDomain

// config
const config = {
  // 版本号
  version: '0.1.1',

  // 域名
  domain: origin,

}

/**
 * 假日表
 * @param [month, day, type, name] type : 1 公历 2 农历
 */

const legalHoliday = [
  ['01', '01', 1, '元旦'],
  ['01', '01', 2, '春节'],
  ['04', '05', 1, '清明节'],
  ['05', '01', 1, '劳动节'],
  ['05', '05', 2, '端午节'],
  ['08', '15', 2, '中秋节'],
  ['10', '01', 1, '国庆节']
]

// 数据字典分类
const dicCode = {
  goodsCategory: '1001', // 商品分类
  Brand: '1002', // 品牌
  category: '1003', // 类别
  doorType: '1004', // 门架种类
  tonnage: '1005' // 吨位
}

export {
  config,
  legalHoliday,
  dicCode
}

 

第三步:

如何封装插件

首先,在angular-cli项目的 src/ 文件夹下新建一个文件夹为 plugins,然后在 plugins/ 下新建 axios.js文件,写入如下代码

import axios from 'axios'
import { config } from './config'

// 定义加载动画
// let loading = null
// let loadingShow = false

// axios.defaults.baseURL = 'http://172.20.1.148:8082'

// 添加请求拦截器
axios.interceptors.request.use(
  conf => {
    // 配置axios请求的url  ${config.ajaxUrl} 是配置的请求url统一前缀,配置好就不用重复写一样的url前缀了,只写后面不同的就可以了
    conf.url = `${config.domain}${conf.url}`

    // 显示加载动画
    // if (!loadingShow) {
    //   loadingShow = true
    //   loading = message.loading('数据加载中...', 0)
    // }

    // 设置 token 判断是否存在token,如果存在的话,则每个http header都加上token
    // if (sessionStorage.getItem('auth')) {
    //   conf.headers['Authorize'] = sessionStorage.getItem('auth')
    // }

    return conf
  },
  error => {
    // 抛出请求错误信息
    Promise.reject(error.response)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 请求失败处理
    return Promise.reject(error)
  }
)

export default axios

 

 第四步:

在组件中使用axios

angular-cli中axios请求拦截、响应拦截的配置

import { Component, OnInit } from '@angular/core'
// 引入 Router
import {
  ActivatedRoute,
  Router,
  ActivatedRouteSnapshot,
  RouterState,
  RouterStateSnapshot
} from '@angular/router'

import axios from '../../plugins/axios'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
  // 注册 Router
  constructor(public router: Router) {}

  ngOnInit() {
    this.allList()
  }

  allList() {
    axios.get(`/back/common/getVerifyCode`).then(res => {})
  }
}

第五步:

重启项目,查看效果

angular-cli中axios请求拦截、响应拦截的配置