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)}`)
    }
  }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。