当前位置:   article > 正文

华为鸿蒙应用--登录页:网络请求、自定义Loading、MD5密码加密、emitter订阅状态变化、持久化登录状态、隐藏软键盘-ArkTs_鸿蒙arkts 在网络请求是现实loading

鸿蒙arkts 在网络请求是现实loading

HarmonyOS系列

华为鸿蒙应用--底部导航栏Tabs(自适应手机和平板)-ArkTs_华为鸿蒙应用 csdn 底部导航栏-CSDN博客

华为鸿蒙应用--欢迎页SplashPage+倒计时跳过(自适应手机和平板)-ArkTs_app.media.ic_splash_page_background-CSDN博客

华为鸿蒙应用--封装数据持久化工具:首选项Preferences(鸿蒙工具)-ArkTs-CSDN博客


效果

通过登录页实现HarmonyOS网络请求、自定义Loading、MD5密码加密、emitter订阅状态变化、持久化登录状态、隐藏软键盘

0、LoginPage.ets代码

  1. import { Constants } from '@ohos/common/src/main/ets/constants/Constants'
  2. import { Logger } from '@ohos/common/src/main/ets/utils/Logger'
  3. import { loginModel } from '../viewmodel/types'
  4. import { CustomDialogView, HttpUtils, PageConstants, PFUKey, PFUtils } from '@ohos/common'
  5. import { Md5 } from 'ts-md5';
  6. import router from '@ohos.router'
  7. import inputMethod from '@ohos.inputMethod'
  8. @Extend(Text) function text16fp333() {
  9. .fontColor($r('app.color.color_333333'))
  10. .fontSize($r('app.float.middle_font_size'))
  11. .fontWeight(FontWeight.Medium)
  12. }
  13. @Extend(TextInput) function inputTrBg() {
  14. .margin({
  15. left: $r('app.float.vp_thirty_two'),
  16. right: $r('app.float.vp_thirty_two') })
  17. .height(50)
  18. .backgroundColor($r('app.color.color_transparent'))
  19. .fontSize($r('app.float.middle_font_size'))
  20. .fontWeight(FontWeight.Medium)
  21. }
  22. @Extend(Line) function line() {
  23. .width(Constants.FULL_PARENT)
  24. .height($r('app.float.vp_zero_point_five'))
  25. .backgroundColor($r('app.color.color_E0E0E0'))
  26. }
  27. @Entry
  28. @Component
  29. struct LoginPage {
  30. private loginModel: loginModel;
  31. private account: string;
  32. private password: string;
  33. build() {
  34. RelativeContainer() {
  35. Column() {
  36. Image($r('app.media.img_logo'))
  37. .height(44)
  38. Text($r('app.string.str_login_by_password'))
  39. .fontColor($r('app.color.black'))
  40. .fontSize($r('app.float.bigger_font_size'))
  41. .margin({ top: $r('app.float.vp_ten') })
  42. .key("123")
  43. }
  44. .alignItems(HorizontalAlign.Start)
  45. .alignRules({
  46. top: { anchor: '__container__', align: VerticalAlign.Top },
  47. left: { anchor: '__container__', align: HorizontalAlign.Start }
  48. })
  49. .margin({ top: 80, left: $r('app.float.vp_thirty_two') })
  50. .id("c_top")
  51. Column() {
  52. Row() {
  53. Text($r('app.string.str_account'))
  54. .text16fp333()
  55. TextInput({ placeholder: $r('app.string.str_account_hint'), text: "13595432224" })
  56. .inputTrBg()
  57. .type(InputType.PhoneNumber)
  58. .onChange((value: string) => {
  59. this.account = value
  60. })
  61. };
  62. Line()
  63. .line()
  64. Row() {
  65. Text($r('app.string.str_password'))
  66. .text16fp333()
  67. TextInput({ placeholder: $r('app.string.str_password_hint'), text: "dho123456" })
  68. .inputTrBg()
  69. .type(InputType.Password)
  70. .onChange((value: string) => {
  71. this.password = value
  72. })
  73. };
  74. Line()
  75. .line()
  76. Button($r('app.string.str_login_now'), { type: ButtonType.Normal, stateEffect: true })
  77. .borderRadius($r('app.float.vp_five'))
  78. .backgroundColor($r('app.color.color_3662EC'))
  79. .width(Constants.FULL_PARENT)
  80. .margin({
  81. top: $r('app.float.vp_twenty')
  82. })
  83. .height($r('app.float.vp_forty'))
  84. .onClick(() => {
  85. let params = {
  86. user_id: this.account,
  87. password: Md5.hashStr(this.password) // md5加密密码
  88. }
  89. HttpUtils.post(HttpUtils.LOGIN_BY_PASSWORD_URL, params, true)
  90. .then((res) => {
  91. this.loginModel = JSON.parse(res)
  92. PFUtils.put(PFUKey.IS_LOGIN, true); // 首选项记录已经登录
  93. HttpUtils.defaultParams("token", this.loginModel.token) // 网络请求默认参数token(authorization)
  94. router.replaceUrl({ url: PageConstants.MAIN_PAGE_URL }) // 跳转首页
  95. })
  96. });
  97. Button($r('app.string.str_register_now'), { type: ButtonType.Normal, stateEffect: true })
  98. .borderRadius($r('app.float.vp_five'))
  99. .backgroundColor($r('app.color.color_transparent'))
  100. .borderStyle(BorderStyle.Solid)
  101. .borderWidth($r('app.float.vp_one'))
  102. .borderColor($r('app.color.color_3662EC'))
  103. .borderRadius($r('app.float.vp_five'))
  104. .width(Constants.FULL_PARENT)
  105. .fontColor($r('app.color.color_3662EC'))
  106. .margin({
  107. top: $r('app.float.vp_twenty')
  108. })
  109. .height($r('app.float.vp_forty'))
  110. .onClick(() => {
  111. HttpUtils.post(HttpUtils.USER_INFO_URL)
  112. .then((res) => {
  113. Logger.error(Constants.TAG, JSON.stringify(res))
  114. })
  115. })
  116. }
  117. .alignRules({
  118. center: { anchor: '__container__', align: VerticalAlign.Center },
  119. left: { anchor: '__container__', align: HorizontalAlign.Start }
  120. })
  121. .margin({
  122. left: $r('app.float.vp_thirty_two'),
  123. right: $r('app.float.vp_thirty_two')
  124. })
  125. .alignItems(HorizontalAlign.Start)
  126. .id("c_center")
  127. CustomDialogView().id("load");
  128. }
  129. .height('100%')
  130. .width("100%")
  131. .backgroundColor($r('app.color.color_F3F4F6'))
  132. .onClick(() => {
  133. let im = inputMethod.getController()
  134. im.stopInputSession() // 隐藏软键盘
  135. });
  136. }
  137. }

1、网络请求HttpsUtils.ets

使用第三方Axios库:OpenHarmony-SIG/ohos_axios

使用该库时,在配置全局请求参数时失效(可能是我使用方法错误),所以自定义补充实现了:defaultParams方法

同时实现了网络请求的loading

  1. import emitter from '@ohos.events.emitter';
  2. import { EmitterId } from '../constants/EmitterId';
  3. import axios, {
  4. AxiosError,
  5. AxiosResponse,
  6. AxiosProgressEvent,
  7. InternalAxiosRequestConfig,
  8. AxiosRequestConfig,
  9. } from '@ohos/axios'
  10. import { Constants } from '../constants/Constants';
  11. import { HttpData, loginModel } from '../viewmodel/types';
  12. import promptAction from '@ohos.promptAction';
  13. import { Logger } from './Logger';
  14. import { PFUtils } from './PFUtils';
  15. import { PFUKey } from '../constants/PFUKey';
  16. export interface param {
  17. paramKey: string,
  18. paramValue: string,
  19. }
  20. export class HttpUtils {
  21. static readonly BASE_URL: string = "http://192.168.1.10:10110/"; // 基础Url
  22. static readonly LOGIN_BY_PASSWORD_URL: string = "password/login"; // 密码登录
  23. static readonly USER_INFO_URL: string = "user/data"; // 用户信息
  24. static async defaultParams(key: string, value: string) {
  25. let param = { paramKey: key, paramValue: value }
  26. let arrParams: Array<param>
  27. PFUtils.get(PFUKey.DEFAULT_PARAMS).then((res: string) => {
  28. if (res === undefined) {
  29. arrParams = []
  30. } else {
  31. arrParams = JSON.parse(res);
  32. }
  33. let index = arrParams.findIndex(item => item.paramKey === key)
  34. if (index === -1) {
  35. arrParams.push(param)
  36. } else {
  37. arrParams[index].paramValue = value;
  38. }
  39. PFUtils.put(PFUKey.DEFAULT_PARAMS, JSON.stringify(arrParams))
  40. })
  41. }
  42. static async post(url: string, params?: any, noDefaultParam?: boolean) {
  43. if (params === undefined) {
  44. params = {}
  45. }
  46. let resp;
  47. this.showLoad(true);
  48. if (!noDefaultParam) {
  49. await PFUtils.get(PFUKey.DEFAULT_PARAMS).then((value: string) => {
  50. if (value !== undefined) {
  51. let arrParams: Array<param>;
  52. arrParams = JSON.parse(value);
  53. for (let index = 0; index < arrParams.length; index++) {
  54. const element = arrParams[index];
  55. params[element.paramKey] = element.paramValue
  56. }
  57. }
  58. })
  59. }
  60. Logger.debug(Constants.HTTP_TAG, "Url:" + this.BASE_URL + url)
  61. Logger.debug(Constants.HTTP_TAG, "Param:" + JSON.stringify(params))
  62. await axios.post(this.BASE_URL + url, params)
  63. .then((res: AxiosResponse<HttpData>) => {
  64. resp = JSON.stringify(res.data.data);
  65. setTimeout(() => {
  66. this.showLoad(false);
  67. promptAction.showToast({
  68. message: res.data.message
  69. })
  70. }, 500); // 延迟500毫秒隐藏Loading,
  71. Logger.debug(Constants.HTTP_TAG, "Data:" + resp)
  72. }).catch((err: AxiosError) => {
  73. setTimeout(() => {
  74. this.showLoad(false);
  75. promptAction.showToast({
  76. message: err.message
  77. })
  78. }, 500);
  79. resp = JSON.stringify(err)
  80. Logger.error(Constants.HTTP_TAG, "Err:" + JSON.stringify(err));
  81. });
  82. return resp;
  83. }
  84. static showLoad(show: boolean) {
  85. emitter.emit({
  86. eventId: EmitterId.LOAD_PROGRESS,
  87. priority: emitter.EventPriority.IMMEDIATE
  88. }, {
  89. data: {
  90. "showLoad": show
  91. }
  92. });
  93. }
  94. }

0、HttpData、loginModel

  1. export interface HttpData<T = any> {
  2. code?: number,
  3. message?: string,
  4. data?: T
  5. }
  6. export interface loginModel {
  7. token?: string,
  8. user_id?: string,
  9. }

1.自定义loading

  1. import emitter from '@ohos.events.emitter';
  2. import { EmitterId } from '../../constants/EmitterId';
  3. import { LoadingProgressDialog } from './LoadingProgressDialog'
  4. export class CustomDialogCallback {
  5. confirmCallback: Function = () => {
  6. };
  7. cancelCallback: Function = () => {
  8. };
  9. }
  10. @Component
  11. export struct CustomDialogView {
  12. @Provide dialogCallBack: CustomDialogCallback = new CustomDialogCallback();
  13. loadingDialog: CustomDialogController = new CustomDialogController({
  14. builder: LoadingProgressDialog(),
  15. autoCancel: true,
  16. customStyle: true
  17. });
  18. aboutToAppear() {
  19. let innerEvent = {
  20. eventId: EmitterId.LOAD_PROGRESS
  21. };
  22. emitter.on(innerEvent, (eventData) => {
  23. if (eventData.data.showLoad) {
  24. if (this.loadingDialog) {
  25. this.loadingDialog.open();
  26. }
  27. } else {
  28. if (this.loadingDialog) {
  29. this.loadingDialog.close();
  30. }
  31. }
  32. });
  33. }
  34. aboutToDisappear() {
  35. emitter.off(EmitterId.LOAD_PROGRESS)
  36. }
  37. build() {
  38. }
  39. }
  40. @CustomDialog
  41. export struct LoadingProgressDialog {
  42. controller: CustomDialogController = new CustomDialogController({ builder: '' });
  43. build() {
  44. Column() {
  45. LoadingProgress()
  46. .width(80)
  47. .height(80)
  48. .color("#FF0000");
  49. Text("加载中...")
  50. .margin({ top: $r('app.float.vp_ten'), bottom: $r('app.float.vp_ten') });
  51. }
  52. .width(140)
  53. .height(160)
  54. .alignItems(HorizontalAlign.Center)
  55. .justifyContent(FlexAlign.Center)
  56. .borderRadius($r('app.float.vp_ten'))
  57. .backgroundColor($r('app.color.white'))
  58. }
  59. }
 

总结

后面继续补充网络请求其他方法:get、delete、上传、下载等

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/314107
推荐阅读
相关标签
  

闽ICP备14008679号