Angular request

来自ling
跳转至: 导航搜索

依赖

axios,lodash,path-to-regexp

工具类

import axios from 'axios';
import lodash from 'lodash';
import { compile, parse } from 'path-to-regexp';


import { environment } from '@env/environment';
import { ServerConstants } from '@shared/constants/server.constants';
import { UuidUtil } from '@shared/util/uuid.util';
import { SessionManager } from '@base/session/session-manager';

const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options;

  let cloneData = lodash.cloneDeep(data);

  let headers = {
    'request-timestamp': String(new Date().getTime()).toString(),
    'request-uuid': UuidUtil.generateUuid(),
    'service-token': SessionManager.getServiceToken(),
    'user-id': SessionManager.getUserId(),
  };

  try {
    let domin = '';

    // 统一加上服务端前缀
    if (
      !url.startsWith('https://') &&
      !url.startsWith('http://') &&
      !url.startsWith('assets/') &&
      !url.startsWith('styles/') &&
      !url.startsWith('testing/')
    ) {
      if (
        url.startsWith(ServerConstants.WEBSOCKET) ||
        url.startsWith('/' + ServerConstants.WEBSOCKET)
      ) {
        url =
          environment.WEBSOCKET_SERVER_URL +
          (url.startsWith('/')
            ? url.substring(ServerConstants.WEBSOCKET.length + 1)
            : url.substring(ServerConstants.WEBSOCKET.length));
      } else if (
        url.startsWith(ServerConstants.BASE) ||
        url.startsWith('/' + ServerConstants.BASE)
      ) {
        url =
          environment.BASE_SERVER_URL +
          (url.startsWith('/')
            ? url.substring(ServerConstants.BASE.length + 1)
            : url.substring(ServerConstants.BASE.length));
      } else if (
        url.startsWith(ServerConstants.IIT) ||
        url.startsWith('/' + ServerConstants.IIT)
      ) {
        url =
          environment.IIT_SERVER_URL +
          (url.startsWith('/')
            ? url.substring(ServerConstants.IIT.length + 1)
            : url.substring(ServerConstants.IIT.length));
      } else {
        url = environment.DEFAULT_SERVER_URL + url;
      }
    }
    console.log('Sending: ' + url);

    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0];
      url = url.slice(domin.length);
    }
    url = compile(url)(data);

    // const match = parse(url);
    // for (const item of match) {
    //   if (item instanceof Object && item.name in cloneData) {
    //     delete cloneData[item.name];
    //   }
    // }
    url = domin + url;
  } catch (e) {
    // message.error(e.message);
  }

  switch (method.toLowerCase()) {
    case 'get':
      cloneData = cloneData ? { ...cloneData, timeSpan: new Date() } : { timeSpan: new Date() }; // 解决ie上的缓存bug
      return axios.get(url, {
        headers: headers,
        params: cloneData,
      });
    case 'delete':
      return axios.delete(url, {
        headers: headers,
        data: cloneData,
      });
    case 'post':
      return axios.post(url, cloneData, {
        headers: headers,
      });
    case 'put':
      return axios.put(url, cloneData, {
        headers: headers,
      });
    case 'patch':
      return axios.patch(url, cloneData, {
        headers: headers,
      });
    default:
      return axios(options);
  }
};

export default function request(options) {
  return fetch(options).then((response: any) => {//AxiosResponse
    const { statusText, status } = response;
    //正常返回
    if (response.status >= 200 && response.status < 300) {
      const { data } = response;
      if (data) {
        const { success, statusCode } = data;
        if (statusCode) {//标准数据
          // const returndata = {
          //   success: true,
          //   messageInfo: statusText,
          //   statusCode: statusCode,
          //   ...data,
          // };
          return data;
        } else {//非标准数据
          const returndata = {
            success: true,
            messageInfo: statusText,
            statusCode: status,
            result: data,
          };
          return returndata;
        }
      } else {
        return { success: true, statusCode: status, messageInfo: null, result: null };
      }
    } else {//非正常返回
      let info;
      if (status === -1) {
        info = '远程服务器无响应';
      } else if (status === 404) {
        info = '找不到资源';
      } else if (status === 401) { // 没有权限
        // window.location.href = loginpath;
        info = '请求的服务受限,请使用其他账号登录';
      } else {
        info = '请求的服务发生错误:' + statusText;
      }
      return { success: false, statusCode: status, messageInfo: info };
    }
    // return data;
  }).catch((error: any) => {//AxiosError
    const { response } = error;
    let msg;
    let statusCode;
    if (response && response instanceof Object) {
      const { data, statusText } = response;
      statusCode = response.status;
      msg = data.message || statusText;
    } else {
      statusCode = 600;
      msg = error.message || 'Network Error';
    }
    return { success: false, statusCode, messageInfo: msg };
  });
}

function log(msg) {
  // console.log(msg);
}


使用

  public getHousingRent(basePersonalInfoUuid):Promise<ServiceResponse<HousingRentVo[]>> {
    const url = 'base/basePersonalInfo/getBasePersonalInfoRentalVosByPersonId';
    return request({
      url: url,
      method: 'get',
      data: { basePersonalInfoUuid: basePersonalInfoUuid },
    });
  };


  public updateBasePersonalInfoRentalVosByPersonId(basePersonalInfoUuid: string, basePersonalInfoRentalVos: HousingRentVo[]):Promise<ServiceResponse<void>> {
    const url = 'base/basePersonalInfo/updateBasePersonalInfoRentalVosByPersonId?basePersonalInfoUuid=' + basePersonalInfoUuid;
    return request({
      url: url,
      method: 'post',
      data: basePersonalInfoRentalVos
    });
  }


 public async getHousingRentData() {
    this.basePersonalInfoUuid = '5babd18573bc0001';
    const res: ServiceResponse<HousingRentVo[]> = await this.personinfoService.getHousingRent(this.basePersonalInfoUuid)
    // console.log(res);
    if (res.success) {
      for (var i = 0; i < res.result.length; i++) {
        let item = res.result[i];
        if (item.startDate !== null) {
          item.startDate = new Date(item.startDate);
        }
        if (item.endDate !== null) {
          item.endDate = new Date(item.endDate);
        }
      }
      this.rentGrid = res.result;
      // this.notification.create('success', '提示', '租金数据加载成功');
    }
  }

  public async saveHousingRentData() {
    let datas = [];
    this.basePersonalInfoUuid = '5babd18573bc0001';
    let rents = this.rentGrid;
    for (var i = 0; i < rents.length; i++) {
      let vo = rents[i];
      if (vo.editStatus == 'DELETE') {
        if (vo.basePersonalInfoRentaluuid != null) {
          datas.push(vo);
        }
      } else if (vo.editStatus == null) {
        vo.editStatus = 'UPDATE';
        datas.push(vo);
      } else {
        datas.push(vo);
      }
    }
    let res = await this.personinfoService.updateBasePersonalInfoRentalVosByPersonId(this.basePersonalInfoUuid, datas);
    if (res.success) {
      this.notification.create('success', '提示', '数据保存成功');
      this.getHousingRentData();
    } else {
      this.notification.create('error', '提示', '数据保存失败:' + res.messageInfo);
    }