第一步:
npm 安裝axios锚国,文件根目錄下安裝,指令如下
npm install axios --save //安裝到生產(chǎn)環(huán)境
第二步:
配置 文件玄坦,它是整個項目的統(tǒng)一配置文件血筑,方便我們管理項目
在angular-cli項目的 文件夾下新建一個文件夾為
绘沉,然后在 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'
// 環(huán)境變量
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 農(nóng)歷
*/
const legalHoliday = [
['01', '01', 1, '元旦'],
['01', '01', 2, '春節(jié)'],
['04', '05', 1, '清明節(jié)'],
['05', '01', 1, '勞動節(jié)'],
['05', '05', 2, '端午節(jié)'],
['08', '15', 2, '中秋節(jié)'],
['10', '01', 1, '國慶節(jié)']
]
// 數(shù)據(jù)字典分類
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統(tǒng)一前綴喻喳,配置好就不用重復(fù)寫一樣的url前綴了另玖,只寫后面不同的就可以了
conf.url = `${config.domain}${conf.url}`
// 顯示加載動畫
// if (!loadingShow) {
// loadingShow = true
// loading = message.loading('數(shù)據(jù)加載中...', 0)
// }
// 設(shè)置 token 判斷是否存在token,如果存在的話表伦,則每個http header都加上token
// if (sessionStorage.getItem('auth')) {
// conf.headers['Authorize'] = sessionStorage.getItem('auth')
// }
return conf
},
error => {
// 拋出請求錯誤信息
Promise.reject(error.response)
}
)
// 添加響應(yīng)攔截器
axios.interceptors.response.use(
response => {
return response.data
},
error => {
// 請求失敗處理
return Promise.reject(error)
}
)
export default axios
第四步:
在組件中使用axios
image.png
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 => {})
}
}
第五步:
重啟項目日矫,查看效果
image.png