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

本文主要是介绍华为鸿蒙应用--登录页:网络请求、自定义Loading、MD5密码加密、emitter订阅状态变化、持久化登录状态、隐藏软键盘-ArkTs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

HarmonyOS系列

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

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

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


效果

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

0、LoginPage.ets代码

import { Constants } from '@ohos/common/src/main/ets/constants/Constants'
import { Logger } from '@ohos/common/src/main/ets/utils/Logger'
import { loginModel } from '../viewmodel/types'
import { CustomDialogView, HttpUtils, PageConstants, PFUKey, PFUtils } from '@ohos/common'
import { Md5 } from 'ts-md5';
import router from '@ohos.router'
import inputMethod from '@ohos.inputMethod'@Extend(Text) function text16fp333() {.fontColor($r('app.color.color_333333')).fontSize($r('app.float.middle_font_size')).fontWeight(FontWeight.Medium)
}@Extend(TextInput) function inputTrBg() {.margin({left: $r('app.float.vp_thirty_two'),right: $r('app.float.vp_thirty_two') }).height(50).backgroundColor($r('app.color.color_transparent')).fontSize($r('app.float.middle_font_size')).fontWeight(FontWeight.Medium)
}@Extend(Line) function line() {.width(Constants.FULL_PARENT).height($r('app.float.vp_zero_point_five')).backgroundColor($r('app.color.color_E0E0E0'))
}@Entry
@Component
struct LoginPage {private loginModel: loginModel;private account: string;private password: string;build() {RelativeContainer() {Column() {Image($r('app.media.img_logo')).height(44)Text($r('app.string.str_login_by_password')).fontColor($r('app.color.black')).fontSize($r('app.float.bigger_font_size')).margin({ top: $r('app.float.vp_ten') }).key("123")}.alignItems(HorizontalAlign.Start).alignRules({top: { anchor: '__container__', align: VerticalAlign.Top },left: { anchor: '__container__', align: HorizontalAlign.Start }}).margin({ top: 80, left: $r('app.float.vp_thirty_two') }).id("c_top")Column() {Row() {Text($r('app.string.str_account')).text16fp333()TextInput({ placeholder: $r('app.string.str_account_hint'), text: "13595432224" }).inputTrBg().type(InputType.PhoneNumber).onChange((value: string) => {this.account = value})};Line().line()Row() {Text($r('app.string.str_password')).text16fp333()TextInput({ placeholder: $r('app.string.str_password_hint'), text: "dho123456" }).inputTrBg().type(InputType.Password).onChange((value: string) => {this.password = value})};Line().line()Button($r('app.string.str_login_now'), { type: ButtonType.Normal, stateEffect: true }).borderRadius($r('app.float.vp_five')).backgroundColor($r('app.color.color_3662EC')).width(Constants.FULL_PARENT).margin({top: $r('app.float.vp_twenty')}).height($r('app.float.vp_forty')).onClick(() => {let params = {user_id: this.account,password: Md5.hashStr(this.password) // md5加密密码}HttpUtils.post(HttpUtils.LOGIN_BY_PASSWORD_URL, params, true).then((res) => {this.loginModel = JSON.parse(res)PFUtils.put(PFUKey.IS_LOGIN, true); // 首选项记录已经登录HttpUtils.defaultParams("token", this.loginModel.token) // 网络请求默认参数token(authorization)router.replaceUrl({ url: PageConstants.MAIN_PAGE_URL }) // 跳转首页})});Button($r('app.string.str_register_now'), { type: ButtonType.Normal, stateEffect: true }).borderRadius($r('app.float.vp_five')).backgroundColor($r('app.color.color_transparent')).borderStyle(BorderStyle.Solid).borderWidth($r('app.float.vp_one')).borderColor($r('app.color.color_3662EC')).borderRadius($r('app.float.vp_five')).width(Constants.FULL_PARENT).fontColor($r('app.color.color_3662EC')).margin({top: $r('app.float.vp_twenty')}).height($r('app.float.vp_forty')).onClick(() => {HttpUtils.post(HttpUtils.USER_INFO_URL).then((res) => {Logger.error(Constants.TAG, JSON.stringify(res))})})}.alignRules({center: { anchor: '__container__', align: VerticalAlign.Center },left: { anchor: '__container__', align: HorizontalAlign.Start }}).margin({left: $r('app.float.vp_thirty_two'),right: $r('app.float.vp_thirty_two')}).alignItems(HorizontalAlign.Start).id("c_center")CustomDialogView().id("load");}.height('100%').width("100%").backgroundColor($r('app.color.color_F3F4F6')).onClick(() => {let im = inputMethod.getController()im.stopInputSession() // 隐藏软键盘});}
}

1、网络请求HttpsUtils.ets

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

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

同时实现了网络请求的loading

import emitter from '@ohos.events.emitter';
import { EmitterId } from '../constants/EmitterId';
import axios, {AxiosError,AxiosResponse,AxiosProgressEvent,InternalAxiosRequestConfig,AxiosRequestConfig,
} from '@ohos/axios'
import { Constants } from '../constants/Constants';
import { HttpData, loginModel } from '../viewmodel/types';
import promptAction from '@ohos.promptAction';
import { Logger } from './Logger';
import { PFUtils } from './PFUtils';
import { PFUKey } from '../constants/PFUKey';export interface param {paramKey: string,paramValue: string,
}export class HttpUtils {static readonly BASE_URL: string = "http://192.168.1.10:10110/"; // 基础Urlstatic readonly LOGIN_BY_PASSWORD_URL: string = "password/login"; // 密码登录static readonly USER_INFO_URL: string = "user/data"; // 用户信息static async defaultParams(key: string, value: string) {let param = { paramKey: key, paramValue: value }let arrParams: Array<param>PFUtils.get(PFUKey.DEFAULT_PARAMS).then((res: string) => {if (res === undefined) {arrParams = []} else {arrParams = JSON.parse(res);}let index = arrParams.findIndex(item => item.paramKey === key)if (index === -1) {arrParams.push(param)} else {arrParams[index].paramValue = value;}PFUtils.put(PFUKey.DEFAULT_PARAMS, JSON.stringify(arrParams))})}static async post(url: string, params?: any, noDefaultParam?: boolean) {if (params === undefined) {params = {}}let resp;this.showLoad(true);if (!noDefaultParam) {await PFUtils.get(PFUKey.DEFAULT_PARAMS).then((value: string) => {if (value !== undefined) {let arrParams: Array<param>;arrParams = JSON.parse(value);for (let index = 0; index < arrParams.length; index++) {const element = arrParams[index];params[element.paramKey] = element.paramValue}}})}Logger.debug(Constants.HTTP_TAG, "Url:" + this.BASE_URL + url)Logger.debug(Constants.HTTP_TAG, "Param:" + JSON.stringify(params))await axios.post(this.BASE_URL + url, params).then((res: AxiosResponse<HttpData>) => {resp = JSON.stringify(res.data.data);setTimeout(() => {this.showLoad(false);promptAction.showToast({message: res.data.message})}, 500); // 延迟500毫秒隐藏Loading,Logger.debug(Constants.HTTP_TAG, "Data:" + resp)}).catch((err: AxiosError) => {setTimeout(() => {this.showLoad(false);promptAction.showToast({message: err.message})}, 500);resp = JSON.stringify(err)Logger.error(Constants.HTTP_TAG, "Err:" + JSON.stringify(err));});return resp;}static showLoad(show: boolean) {emitter.emit({eventId: EmitterId.LOAD_PROGRESS,priority: emitter.EventPriority.IMMEDIATE}, {data: {"showLoad": show}});}
}

0、HttpData、loginModel


export interface HttpData<T = any> {code?: number,message?: string,data?: T
}export interface loginModel {token?: string,user_id?: string,
}

1.自定义loading

import emitter from '@ohos.events.emitter';
import { EmitterId } from '../../constants/EmitterId';
import { LoadingProgressDialog } from './LoadingProgressDialog'export class CustomDialogCallback {confirmCallback: Function = () => {};cancelCallback: Function = () => {};
}@Component
export struct CustomDialogView {@Provide dialogCallBack: CustomDialogCallback = new CustomDialogCallback();loadingDialog: CustomDialogController = new CustomDialogController({builder: LoadingProgressDialog(),autoCancel: true,customStyle: true});aboutToAppear() {let innerEvent = {eventId: EmitterId.LOAD_PROGRESS};emitter.on(innerEvent, (eventData) => {if (eventData.data.showLoad) {if (this.loadingDialog) {this.loadingDialog.open();}} else {if (this.loadingDialog) {this.loadingDialog.close();}}});}aboutToDisappear() {emitter.off(EmitterId.LOAD_PROGRESS)}build() {}
}@CustomDialog
export struct LoadingProgressDialog {controller: CustomDialogController = new CustomDialogController({ builder: '' });build() {Column() {LoadingProgress().width(80).height(80).color("#FF0000");Text("加载中...").margin({ top: $r('app.float.vp_ten'), bottom: $r('app.float.vp_ten') });}.width(140).height(160).alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Center).borderRadius($r('app.float.vp_ten')).backgroundColor($r('app.color.white'))}
}
 

总结

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

这篇关于华为鸿蒙应用--登录页:网络请求、自定义Loading、MD5密码加密、emitter订阅状态变化、持久化登录状态、隐藏软键盘-ArkTs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/548564

相关文章

关于WebSocket协议状态码解析

《关于WebSocket协议状态码解析》:本文主要介绍关于WebSocket协议状态码的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录WebSocket协议状态码解析1. 引言2. WebSocket协议状态码概述3. WebSocket协议状态码详解3

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

springboot security验证码的登录实例

《springbootsecurity验证码的登录实例》:本文主要介绍springbootsecurity验证码的登录实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录前言代码示例引入依赖定义验证码生成器定义获取验证码及认证接口测试获取验证码登录总结前言在spring

Python中随机休眠技术原理与应用详解

《Python中随机休眠技术原理与应用详解》在编程中,让程序暂停执行特定时间是常见需求,当需要引入不确定性时,随机休眠就成为关键技巧,下面我们就来看看Python中随机休眠技术的具体实现与应用吧... 目录引言一、实现原理与基础方法1.1 核心函数解析1.2 基础实现模板1.3 整数版实现二、典型应用场景2

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

SpringBoot使用OkHttp完成高效网络请求详解

《SpringBoot使用OkHttp完成高效网络请求详解》OkHttp是一个高效的HTTP客户端,支持同步和异步请求,且具备自动处理cookie、缓存和连接池等高级功能,下面我们来看看SpringB... 目录一、OkHttp 简介二、在 Spring Boot 中集成 OkHttp三、封装 OkHttp

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda