国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

鴻蒙【ArkTS】封裝數(shù)據(jù)請(qǐng)求HTTP 使用裝飾器進(jìn)行配置化引入接口

這篇具有很好參考價(jià)值的文章主要介紹了鴻蒙【ArkTS】封裝數(shù)據(jù)請(qǐng)求HTTP 使用裝飾器進(jìn)行配置化引入接口。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

鴻蒙【ArkTS】封裝數(shù)據(jù)請(qǐng)求HTTP 使用裝飾器進(jìn)行配置化引入接口

官方API文檔:數(shù)據(jù)請(qǐng)求HTTP

實(shí)現(xiàn)步驟:

一、統(tǒng)一接口請(qǐng)求結(jié)果

export class ApiResult {
  code : string
  msg ?: string
  data ?: any
}

二、網(wǎng)絡(luò)請(qǐng)求配置類

/**
 * <pre>
 * @desc  : 網(wǎng)絡(luò)請(qǐng)求配置
 * </pre>
 */
export interface RequestOptions {

  /**
   * Request url.
   */
  url?: string;

  /**
   * Request method.
   */
  method?: RequestMethod; // default is GET

  /**
   * Additional data of the request.
   * extraData can be a string or an Object (API 6) or an ArrayBuffer(API 8).
   */
  extraData?: string | Object | ArrayBuffer;

  /**
   * Request url queryParams  .
   */
  queryParams ?: Record<string, string>;

  /**
   * HTTP request header.
   */
  header?: Object; // default is 'content-type': 'application/json'

}

export enum RequestMethod {
  OPTIONS = "OPTIONS",
  GET = "GET",
  HEAD = "HEAD",
  POST = "POST",
  PUT = "PUT",
  DELETE = "DELETE",
  TRACE = "TRACE",
  CONNECT = "CONNECT"
}

三、網(wǎng)絡(luò)請(qǐng)求核心類 引用官方Api

import http from '@ohos.net.http';
import { RequestOptions } from './RequestOptions';
import { ApiResult } from '../ApiResult/ApiResult';
// 引入彈窗
import PreferenceUtil from '../../utils/PreferenceUtil'
import promptAction from '@ohos.promptAction';
import { LoadingProgressDialog } from '../../utils/LoadingProgressDialog';
import router from '@ohos.router';
/**
 * Http請(qǐng)求器
 */
export class HttpCore {

  loadingDialog: CustomDialogController = new CustomDialogController({
    builder: LoadingProgressDialog(),
    alignment:DialogAlignment.Center,
    autoCancel: true,
    customStyle: true
  });


  /**
   * 發(fā)送請(qǐng)求
   * @param requestOption
   * @returns Promise
   */
  request(requestOptions: RequestOptions): Promise<ApiResult> {
    let p = new Promise<ApiResult>(async (resolve, reject) => {
      // 每一個(gè)httpRequest對(duì)應(yīng)一個(gè)HTTP請(qǐng)求任務(wù),不可復(fù)用
      let httpRequest = http.createHttp();
      let token : string = await getToken();
      let promise = httpRequest.request(requestOptions.url, {
        method: requestOptions.method,
        connectTimeout: 60000,
        readTimeout: 60000,
        header:{
          'Content-Type': 'application/json',
          'token': token,
          'client_type': 'HarmonyOS'
        },
        extraData: requestOptions.extraData
      });
      promise.then((data) => {
        //TODO:此處補(bǔ)充數(shù)據(jù)拆包的操作
        let resultObj = JSON.parse(data.result.toString());
        //彈窗提示接口返回msg
        setTimeout(() => {
          promptAction.showToast({
            message: resultObj.msg
          })
        }, 500);
        //如果業(yè)務(wù)碼為20000 則返回ApiReslut
        if (resultObj.code == 20000) {
          console.log(JSON.stringify(resultObj))
          resolve(resultObj);
        }
        if (resultObj.code == 0){
          router.replaceUrl({
            url: "pages/MainPage/Login"
          }).then(() => {
            console.log('router successful')
          }).catch(err => {
            console.log('router err')
          })
        }
        //如果返回?cái)?shù)據(jù)包含token信息 則刷新token
        if (resultObj.token != undefined)  {
          PreferenceUtil.putPreference('token',resultObj.token)
        }
      }).catch((err) => {
        //這里做全局異常統(tǒng)一處理  根據(jù)Http狀態(tài)碼做出處理
        console.info('error:' + JSON.stringify(err));
        reject(err);
      });
      httpRequest.destroy();
    })
    return p;
  }



}


async function getToken(): Promise<string> {
  return new Promise<string>(async (resolve, reject) => {
    try {
      const data = await PreferenceUtil.getPreference('token');
      if (typeof data === 'string') {
        resolve(data);
      } else {
        reject(new Error('Invalid token'));
      }
    } catch (err) {
      reject(err);
    }
  });

}




export const httpCore = new HttpCore();

四、導(dǎo)出對(duì)外工具類

import { RequestMethod, RequestOptions } from './RequestOptions';
import { httpCore } from './HttpCore';
import { ApiResult } from '../ApiResult/ApiResult';
/**
 * <pre>
 * @desc       : 對(duì)外工具包
 * </pre>
 */
export class HttpUtil {
  private static mInstance: HttpUtil;

  // 防止實(shí)例化
  private constructor() {

  }

  static getInstance(): HttpUtil {
    if (!HttpUtil.mInstance) {
      HttpUtil.mInstance = new HttpUtil();
    }
    return HttpUtil.mInstance;
  }

  request (option: RequestOptions): Promise<ApiResult> {
    return httpCore.request(option);
  }

  /**
   * 封裝Post網(wǎng)絡(luò)請(qǐng)求
   * @param option
   * @returns
   */
  Post(option:RequestOptions){
      if(option != null){
        option.method = RequestMethod.POST
      }
      return this.request(option);
  }

  /**
   * 封裝Get網(wǎng)絡(luò)請(qǐng)求
   * @param option
   * @returns
   */
  Get(option:RequestOptions){
    if(option != null){
      option.method = RequestMethod.GET
    }
    return this.request(option);
  }



}

export const httpUtil = HttpUtil.getInstance();

五、利用裝飾器實(shí)現(xiàn)AOP效果

import { ApiResult } from '../ApiResult/ApiResult';
import { httpUtil } from '../Http/HttpUtil';
import { RequestOptions } from '../Http/RequestOptions';

/**
 * 利用Map保存參數(shù)和值的映射關(guān)系  為避免參數(shù)名及方法名重復(fù) 采用組合Key的方法
 */
type FunParamMapKey = {
  target: Object; //所在類
  methodName: string; //所在方法
  index: number; //參數(shù)名索引值
}

let funParamMap = new Map<string, string>();


// @Get注解 拿到url 從函數(shù)的@Param拿到參數(shù)名及參數(shù)值 利用HttpUtil進(jìn)行網(wǎng)絡(luò)請(qǐng)求
//Get 需要拼接URl
export function Get(url: string) {
  return function (target: any, methodName: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    let URL: string = url;
    let options: RequestOptions = {
      url: URL,
      queryParams: {}
    };
    descriptor.value = async function (...args: any[]) {
      //對(duì)于方法中的每一個(gè)(methodName,arg)遍歷加入到網(wǎng)絡(luò)請(qǐng)求配置中
      args.forEach((arg, index) => {
        // 通過(guò)已知的信息構(gòu)造組合Key對(duì)象
        let obj: FunParamMapKey = { target: target, methodName: methodName, index: index };
        // 通過(guò)組合Key(通過(guò)對(duì)內(nèi)容的比較而不是值 節(jié)省內(nèi)存)從內(nèi)存map中獲取@Param修飾的內(nèi)容
        let paramName = funParamMap[JSON.stringify(obj)];
        // 將正確的參數(shù)名及值添加至網(wǎng)絡(luò)請(qǐng)求參數(shù)中
        if (typeof paramName !== 'undefined') {
          if (typeof arg === 'string' || typeof arg === 'object' || arg instanceof ArrayBuffer || typeof arg === 'number') {
            options.queryParams[paramName] = arg
          } else {
            console.log('參數(shù)類型不對(duì)')
            throw new Error(`Invalid parameter type at index ${index}.`);
          }
        }
      });
      //拼接請(qǐng)求參數(shù)
      const urlParams = Object.keys(options.queryParams).map(key => `${key}=${options.queryParams[key]}`).join('&')
      console.log('urlParams:', urlParams)
      if (URL.includes("?")) {
        options.url = `${URL}${urlParams}`
      } else {
        options.url = `${URL}?${urlParams}`
      }

      const p = new Promise<ApiResult>((resolve, reject) => {
        httpUtil.Get(options).then((response) => {
          const result: ApiResult = response;
          resolve(result);
        }).catch((error) => {
          reject(error);
        });
      });
      return await p;
    };
  };
}

// @Post注解 拿到url 從函數(shù)的@Param拿到參數(shù)名及參數(shù)值 利用HttpUtil進(jìn)行Post網(wǎng)絡(luò)請(qǐng)求
export function Post(url: string) {
  return function (target: any, methodName: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    let options: RequestOptions = {
      url: url,
      extraData: {}
    };
    descriptor.value = async function (...args: any[]) {
      //對(duì)于方法中的每一個(gè)(methodName,arg)遍歷加入到網(wǎng)絡(luò)請(qǐng)求配置中
      args.forEach((arg, index) => {
        console.log("參數(shù)值",JSON.stringify(arg))
        // 通過(guò)已知的信息構(gòu)造組合Key對(duì)象
        let obj: FunParamMapKey = { target: target, methodName: methodName, index: index };
        // 通過(guò)組合Key(通過(guò)對(duì)內(nèi)容的比較而不是值 節(jié)省內(nèi)存)從內(nèi)存map中獲取@Param修飾的內(nèi)容
        let paramName = funParamMap[JSON.stringify(obj)];
        console.log("參數(shù)名:",paramName)
        // 將正確的參數(shù)名及值添加至網(wǎng)絡(luò)請(qǐng)求參數(shù)中
        if (typeof paramName !== 'undefined') {
          if (typeof arg === 'string' || typeof arg === 'object' || arg instanceof ArrayBuffer) {
            options.extraData[paramName] = arg;
          } else {
            throw new Error(`Invalid parameter type at index ${index}.`);
          }
        }else {
          //如果獲取不到形參名 及未被@Param標(biāo)記 并且參數(shù)的類型是對(duì)象
          if (typeof  arg === 'object') {
            options.extraData = JSON.stringify(arg)
          }
        }
      });
      console.log('extraData', JSON.stringify(options.extraData))
      const p = new Promise<ApiResult>((resolve, reject) => {
        httpUtil.Post(options).then((response) => {
          const result: ApiResult = response;
          resolve(result);
        }).catch((error) => {
          reject(error);
        });
      });
      return await p;
    };
  };
}
/**
 * @Param 注解將想要獲取的Param添加至內(nèi)存Map中
 * @param paramName
 * @returns
 */
export function Param(paramName: string) {
  return function (target: any, methodName: string, parameterIndex: number) {
    let obj: FunParamMapKey = { target: target, methodName: methodName, index: parameterIndex };
    funParamMap[JSON.stringify(obj)] = paramName;
  };
}







使用示例:

import{Post, Param} from './aop/aop'
import { ApiResult } from './ApiResult/ApiResult';

export class LoginApi {
  @Post("http://localhost:8080/login")
  //自定義@Param 作用:獲取形參 便于映射到extraData
   login(@Param("username") username: string, @Param("password") password: string):Promise<ApiResult> {
    return
  }
}
export const  loginApi = new LoginApi();


import{Post,Get, Param} from './aop/aop'
import { ApiResult } from './ApiResult/ApiResult';
export class MenuApi {
  @Get("http://localhost:8080/api/menu/getMenuTree")
  getMenuTree():Promise<ApiResult> {
    return
  }

  @Get("http://localhost:8080/api/menu/getPermTree")
  getPermsSelectTree():Promise<ApiResult> {
    return
  }

  //@Get中的@Param 可以將形參拼接到URl中
  @Get("http://localhost:8080/api/menu/get")
  getMenuById(@Param("Id") id : number):Promise<ApiResult> {
    return
  }

}
export const  menuApi = new MenuApi();
import { RoleModel } from '../models/RoleModel';
import{Post,Get, Param} from './aop/aop'
import { ApiResult } from './ApiResult/ApiResult';
export class RoleApi{
  /**
   * 獲取所有角色
   * @returns
   */

  @Get("http://localhost:8080/api/role/getAllRole")
  getAllRole():Promise<ApiResult> {
    return
  }

  //可以直接Post對(duì)象
  @Post("http://localhost:8080/api/role/updateRole")
  updateRole(role : RoleModel):Promise<ApiResult> {
    return
  }

}
export const  roleApi = new RoleApi();

文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-855850.html

到了這里,關(guān)于鴻蒙【ArkTS】封裝數(shù)據(jù)請(qǐng)求HTTP 使用裝飾器進(jìn)行配置化引入接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【HarmonyOS】【ArkTS】如何使用HTTP網(wǎng)絡(luò)請(qǐng)求獲取動(dòng)態(tài)數(shù)據(jù)刷新UI界面

    【】 HttpRequest、ArkTS、網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求、@ohos.net.http 【前言】 在使用ArkTS開(kāi)發(fā)HarmonyOS應(yīng)用時(shí),需要調(diào)用HTTP網(wǎng)絡(luò)請(qǐng)求?@ohos.net.http?動(dòng)態(tài)獲取數(shù)據(jù),進(jìn)行UI列表刷新,這想必是應(yīng)用開(kāi)發(fā)最常見(jiàn)的功能。但是根據(jù)官網(wǎng)網(wǎng)絡(luò)請(qǐng)求的示例代碼進(jìn)行功能開(kāi)發(fā)時(shí),封裝方法進(jìn)行HTTP請(qǐng)求后

    2024年02月08日
    瀏覽(23)
  • 鴻蒙harmony--HTTP數(shù)據(jù)請(qǐng)求的簡(jiǎn)單使用

    ?不得不承認(rèn),年齡越大性格就越簡(jiǎn)單,更喜歡安靜,不喜歡去了解別人,也不想被了解,只想靜靜的做自己喜歡的事…… 目錄 一,場(chǎng)景介紹 二,接口說(shuō)明 三,http請(qǐng)求使用 應(yīng)用通過(guò)HTTP發(fā)起一個(gè)數(shù)據(jù)請(qǐng)求,支持常見(jiàn)的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 HT

    2024年01月20日
    瀏覽(20)
  • 【HarmonyOS開(kāi)發(fā)】ArkTs使用Http封裝

    【HarmonyOS開(kāi)發(fā)】ArkTs使用Http封裝

    @ohos/axios @ohos/retrofit @ohos/httpclient @ohos.net.http 本模塊提供HTTP數(shù)據(jù)請(qǐng)求能力。應(yīng)用可以通過(guò)HTTP發(fā)起一個(gè)數(shù)據(jù)請(qǐng)求,支持常見(jiàn)的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 http.createHttp(創(chuàng)建請(qǐng)求實(shí)例任務(wù)); request(請(qǐng)求); destroy(中斷請(qǐng)求); on(訂閱HTTP Response H

    2024年01月22日
    瀏覽(17)
  • Arkts http數(shù)據(jù)請(qǐng)求

    使用Arkts功能需要申請(qǐng)ohos.permission.INTERNET權(quán)限。即在module.json5文件中申明網(wǎng)絡(luò)訪問(wèn)權(quán)限:ohos.permission.INTERNET。如下 Arkts http數(shù)據(jù)請(qǐng)求功能主要由http模塊提供。具體接口說(shuō)明如下表。 接口名 功能描述 createHttp() 創(chuàng)建一個(gè)http請(qǐng)求。 request() 根據(jù)URL地址,發(fā)起HTTP網(wǎng)絡(luò)請(qǐng)求。 destroy

    2024年02月04日
    瀏覽(20)
  • HarmonyOS ArkTS HTTP數(shù)據(jù)請(qǐng)求(九)

    HarmonyOS ArkTS HTTP數(shù)據(jù)請(qǐng)求(九)

    日常生活中我們使用應(yīng)用程序看新聞、發(fā)送消息等,都需要連接到互聯(lián)網(wǎng),從服務(wù)端獲取數(shù)據(jù)。例如,新聞應(yīng)用可以從新聞服務(wù)器中獲取最新的熱點(diǎn)新聞,從而給用戶打造更加豐富、更加實(shí)用的體驗(yàn)。 那么要實(shí)現(xiàn)這樣一種能實(shí)時(shí)從服務(wù)端獲取數(shù)據(jù)的場(chǎng)景,就依賴于HTTP數(shù)據(jù)請(qǐng)

    2024年02月03日
    瀏覽(29)
  • 鴻蒙應(yīng)用開(kāi)發(fā)之HTTP數(shù)據(jù)請(qǐng)求

    鴻蒙應(yīng)用開(kāi)發(fā)之HTTP數(shù)據(jù)請(qǐng)求

    日常生活中我們使用應(yīng)用程序看新聞、發(fā)送消息等,都需要連接到互聯(lián)網(wǎng),從服務(wù)端獲取數(shù)據(jù)。例如,新聞應(yīng)用可以從新聞服務(wù)器中獲取最新的熱點(diǎn)新聞,從而給用戶打造更加豐富、更加實(shí)用的體驗(yàn)。 那么要實(shí)現(xiàn)這樣一種能實(shí)時(shí)從服務(wù)端獲取數(shù)據(jù)的場(chǎng)景,就依賴于HTTP數(shù)據(jù)請(qǐng)

    2024年02月05日
    瀏覽(19)
  • 鴻蒙HarmonyOS-HTTP網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求

    鴻蒙HarmonyOS-HTTP網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求

    應(yīng)用可以通過(guò)HTTP發(fā)起一個(gè)數(shù)據(jù)請(qǐng)求,支持常見(jiàn)的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 親愛(ài)的讀者: 首先,我要感謝您抽出寶貴的時(shí)間閱讀這篇文章。我深知,您的每一分每一秒都是寶貴的。為此,我在創(chuàng)作這篇文章時(shí)付出了巨大的努力,力求為您提供最具價(jià)

    2024年01月16日
    瀏覽(19)
  • 鴻蒙ArkTS小短劇開(kāi)源項(xiàng)目進(jìn)行中

    使用ArtTS語(yǔ)言,API9以上,HarmonyOS系統(tǒng)的短劇開(kāi)源代碼,使用GSYVideoPlayer作為核心播放器的小短劇。主要以ArkTS,ArkUI編寫(xiě)為主,擁有市面上的短劇頁(yè)面。 推薦頁(yè)面,主要隨機(jī)推薦熱門(mén)的小短劇并播放 短劇頁(yè)面,主要是對(duì)短劇類型進(jìn)行了分類,可供選擇。 收藏界面,主要是對(duì)自

    2024年04月16日
    瀏覽(19)
  • 鴻蒙OS開(kāi)發(fā)實(shí)戰(zhàn):【網(wǎng)絡(luò)管理HTTP數(shù)據(jù)請(qǐng)求】

    鴻蒙OS開(kāi)發(fā)實(shí)戰(zhàn):【網(wǎng)絡(luò)管理HTTP數(shù)據(jù)請(qǐng)求】

    應(yīng)用通過(guò)HTTP發(fā)起一個(gè)數(shù)據(jù)請(qǐng)求,支持常見(jiàn)的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 HTTP數(shù)據(jù)請(qǐng)求功能主要由http模塊提供。 使用該功能需要申請(qǐng)ohos.permission.INTERNET權(quán)限。 涉及的接口如下表,具體的接口說(shuō)明請(qǐng)參考API文檔。 接口名 功能描述 createHttp() 創(chuàng)建一個(gè)ht

    2024年04月29日
    瀏覽(19)
  • 【鴻蒙(HarmonyOS)】UI開(kāi)發(fā)的兩種范式:ArkTS、JS(以登錄界面開(kāi)發(fā)為例進(jìn)行對(duì)比)

    【鴻蒙(HarmonyOS)】UI開(kāi)發(fā)的兩種范式:ArkTS、JS(以登錄界面開(kāi)發(fā)為例進(jìn)行對(duì)比)

    之后關(guān)于HarmonyOS技術(shù)的分享,將會(huì)持續(xù)使用到以下版本 HarmonyOS:3.1/4.0 SDK:API 9 Release Node.js:v14.20.1 DevEco Studio: 3.1.0 HarmonyOS應(yīng)用的UI開(kāi)發(fā)依賴于 方舟開(kāi)發(fā)框架(簡(jiǎn)稱ArkUI) 。 根據(jù)官方介紹,ArkUI提供了UI語(yǔ)法、豐富的UI功能(組件、布局、動(dòng)畫(huà)以及交互事件),以及實(shí)時(shí)界面

    2024年02月08日
    瀏覽(16)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包