/** * @description: 地址工具类 * @author ChenRui * @date 2021/1/15 15:37 */ class UrlUtilService { /** * @description: 获取地址 * @author ChenRui * @date 2021/1/15 15:43 */ getPathFromUrl(url: string): string { let path = url; if (url.indexOf("?") !== -1) { path = url.split("?")[0]; } return path; } /** * @description: 获取参数 * @author ChenRui * @date 2021/1/15 15:37 */ getParamsFromUrl(url: string): any { let parameter: any = null; if (url.indexOf("?") !== -1) { parameter = this.urlParameterToParams(url.split("?")[1]); } return parameter; } /** * @description: 参数拼接 * @author ChenRui * @date 2021/1/15 15:38 */ urlParameterToParams(parameter: string): any { const params: any = {}; const arr: string[] = parameter.split("&"); arr.forEach((val: string, idx: number, array: string[]) => { const kv: string[] = val.split("="); if (kv.length > 1) { params[kv[0]] = decodeURIComponent(kv[1]); } else { params[kv[0]] = ""; } }); return params; } /** * @description: 拼接地址与参数 * @author ChenRui * @date 2021/1/15 15:53 */ urlQueryConvert(url: string, parameterMap?: any): string { let connectiveSymbol = ""; if (url.indexOf("?") !== -1) { connectiveSymbol = "&"; } else { connectiveSymbol = "?"; } if (parameterMap) { let mark = 0; Object.keys(parameterMap).forEach(function (key) { if (mark === 0) { if (parameterMap[key] != null && parameterMap[key] !== "null" && parameterMap[key] !== "undefined") { url += connectiveSymbol + key + "=" + parameterMap[key]; } else { url += connectiveSymbol + key + "="; } } else { if (parameterMap[key] != null && parameterMap[key] !== "null" && parameterMap[key] !== "undefined") { url += "&" + key + "=" + parameterMap[key]; } else { url += "&" + key + "="; } } mark++; }); } return url; } /** * @description: 从地址中获取登录响应码 * @author ChenRui * @date 2020/12/18 15:23 */ getQueryValue(queryName: string): string { const query = decodeURI(window.location.search.substring(1)); const vars = query.split("&"); for (let i = 0; i < vars.length; i++) { const pair = vars[i].split("="); if (pair[0] == queryName) { return pair[1]; } } return ""; } /** * @description: 删除参数 * @author ChenRui * @date 2021/1/15 15:40 */ deleteParameter(url: string, ...delParams: string[]): string { const path: string = this.getPathFromUrl(url); const params: any = this.getParamsFromUrl(url); if (params && delParams && delParams.length > 0) { for (const key of Object.keys(params)) { if (delParams.findIndex((item) => item === key) > -1) { delete params[key]; } } } if (params && Object.keys(params).length > 0) { return this.urlQueryConvert(path, params); } else { return path; } } } const urlUtilService = new UrlUtilService(); export { urlUtilService };