v002-HarmonyOS(arkTS)常用功能整理

一、axios网络请求工具类封装

  • 导入相关的库

ohpm install @ohos/axios
  • 请记得添加权限,位置E:*\你的项目\entry\src\main\module.json5**
ohos.permission.INTERNET
  • 如果用到加密方法,那也要导入一下"crypto-js"
ohpm install @ohos/crypto-js
  • 封装方法

import axios, { AxiosError, AxiosResponse } from '@ohos/axios';
import { LogUtils } from '../utils/LogUtils';
import { JSON } from '@kit.ArkTS';
import { CallResult } from '../bean/CallResult';
import { http } from '@kit.NetworkKit';
import { KEY_TOKEN, ShareUtils } from '../utils/ShareUtils';
import { LoginUtils } from '../utils/LoginUtils';

/**
 * 默认请求时长
 */
const DEFAULT_TIMEOUT = 1000 * 20;
/**
 * 默认地址
 */
const Url = 'http://192.168.1.221:880';
axios.defaults.baseURL = 'http://192.168.1.221:880';
axios.defaults.headers.post['Content-Type'] = 'application/json';

export class UrlUtils {
  /**
   * token值
   */
  static TOKEN: string = LoginUtils.getToken();

  public static setSaveToken(token: string) {
    UrlUtils.TOKEN = token;
    ShareUtils.set(KEY_TOKEN, token)
  }

  static get<T>(apiPath: string): Promise<CallResult<T>> {
    return axios<string, AxiosResponse<CallResult<T>>, null>({
      baseURL: Url,
      url: apiPath,
      timeout: DEFAULT_TIMEOUT,
      method: http.RequestMethod.GET,
      headers: {
        'token': UrlUtils.TOKEN
      }
    }).then((resp: AxiosResponse<CallResult<T>>) => {
      UrlUtils.logInfo(apiPath, undefined, resp.data);
      return resp.data;
    }).catch((error: AxiosError) => {
      let data: CallResult<T> = new CallResult<T>()
      data.code = 400
      data.message = error.message
      UrlUtils.logInfo(apiPath, undefined, data);
      return data;
    })
  }

  static post<T>(apiPath: string, params: object): Promise<CallResult<T>> {
    return axios<string, AxiosResponse<CallResult<T>>, object>({
      baseURL: Url,
      url: apiPath,
      timeout: DEFAULT_TIMEOUT,
      method: http.RequestMethod.POST,
      headers: {
        'token': UrlUtils.TOKEN
      },
      data: params,
    }).then((resp: AxiosResponse<CallResult<T>>) => {
      UrlUtils.logInfo(apiPath, params, resp.data);
      return resp.data;
    }).catch((error: AxiosError) => {
      let data: CallResult<T> = new CallResult<T>()
      data.code = 400
      data.message = error.message
      UrlUtils.logInfo(apiPath, params, data);
      return data;
    })
  }

  private static logInfo<T>(apiPath: string, params?: object, data?: CallResult<T>) {
    LogUtils.i("请求地址:" + Url + apiPath)
    if (params != null) {
      LogUtils.i("请求参数:" + JSON.stringify(params))
    }
    if (data != null) {
      LogUtils.i("返回参数:" + JSON.stringify(data))
    }
  }
}
  • 使用方法

  • post方法
let record: Record<string, string> = {
      "phone": this.phone,
      "passWord": ValueUtils.md5(this.pwd)
    }
    let apiPath = '/api/sysuser/login'
    UrlUtils.post<LoginResp>(apiPath, record).then(data => {
      if (data.code == 200 && data.data != null) {
        UrlUtils.setSaveToken(data.data.token)
        ShareUtils.set('userName', data.data.userName);
        router.replaceUrl({ url: 'pages/MainPage' })
      } else {
        ComUtils.toast(data.message)
      }
    })
  • get方法
     UrlUtils.get<UserInfoBean>('/api/sysuser/info').then(data => {
      if (data.code == 200) {
        LogUtils.i("用户信息:" + JSON.stringify(data.data))
      }
    })

二、首选项

  • 封装方法

import { preferences } from '@kit.ArkData';
import { LogUtils } from './LogUtils';

//数据库名称
const LuckDataBase: string = 'LuckDataBase1';

//token名称
export const KEY_TOKEN: string = "Luck_KEY_TOKEN";

export class ShareUtils {
  static options: preferences.Options = { name: LuckDataBase }
  static dataPreferences: preferences.Preferences;

  private static getPreference() {
    if (ShareUtils.dataPreferences == null) {
      ShareUtils.dataPreferences = preferences.getPreferencesSync(getContext(), ShareUtils.options)
    }
    return ShareUtils.dataPreferences;
  }

  static set(key: string, value: string) {
    let dataPreferences = ShareUtils.getPreference();
    dataPreferences.putSync(key, value)
    dataPreferences.flush()
    LogUtils.i(`保存成功:${key},${value}`)
  }

  static remove(key: string) {
    let dataPreferences = ShareUtils.getPreference();
    dataPreferences.deleteSync(key)
  }

  static getString(key: string) {
    let dataPreferences = ShareUtils.getPreference();
    return dataPreferences.getSync(key, '').toString()
  }
}
  • 使用方法

  //保存数据
  ShareUtils.set('userName', data.data.userName);
  //读取数据
  ShareUtils.getString(KEY_TOKEN)

三、其他,如吐司、自定义实体类泛型,日志工具类等

  • 吐司

import promptAction from '@ohos.promptAction';

export default class ComUtils {
  static toast(message: Resource | string) {
    promptAction.showToast({
      message: message,
      duration: 1500
    });
  };
}
//使用方法
ComUtils.toast("请输入密码")
  • 自定义实体类泛型

/**
 * https://developer.huawei.com/consumer/cn/forum/topic/0204148819047359327?fid=0102683795438680754
 * 如果你的class是new出来的,那么方法可用,如果是通过赋值过来的,那么就不可用。
 */
export class CallResult<T> {
  /**
   * 服务器返回的code,为200则请求成功
   */
  code: number;
  /**
   * 服务器返回的回调消息
   */
  message: string;
  /**
   * 指定的泛型
   */
  data?: T;

  constructor() {
    this.code = 0;
    this.message = '';
  }
  static isSuccess<T>(data: CallResult<T>) {
    return data.code == HttpStatusCode.Ok;
  }

  static isSuccessAndNotNull<T>(data: CallResult<T>) {
    return this.isSuccess(data) && data.data != null;
  }
}
  • 日志工具类

export default class LogUtils {
  private static TAG: string = "excc";

  static i(info: any): void {
    if(info==null || info == undefined){
      return
    }
    if (info instanceof Number || info instanceof String || info instanceof Boolean) {
      console.info(`${this.TAG}:${info}`)
    } else {
      console.info(`${this.TAG}:${JSON.stringify(info)}`)
    }
  }

  static e(error: any): void {
    if(error==null || error == undefined){
      return
    }
    if (error instanceof Number || error instanceof String || error instanceof Boolean) {
      console.error(`${this.TAG}:${error}`)
    } else {
      console.error(`${this.TAG}:${JSON.stringify(error)}`)
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。