当前位置:   article > 正文

HarmonyOS Next 实现登录注册页面(ARKTS) 并使用Springboot作为后端提供接口_arkts登录注册界面

arkts登录注册界面

1. HarmonyOS next

ArkTS

ArkTS围绕应用开发在 TypeScript (简称TS)生态基础上做了进一步扩展,继承了TS的所有特性,是TS的超集

ArkTS在TS的基础上扩展了struct和很多的装饰器以达到描述UI和状态管理的目的

以下代码是一个基于 HarmonyOS 的登录页面组件的示例代码,主要实现了用户登录功能以及一些数据存储和页面跳转的操作。下面我会逐步解释每个部分并添加注释:

2. 实例

3. 功能分区

1.1. HTTP获取后台接口数据,以下是示例

  1. async jwt(jwt: string) {
  2. try {
  3. const res = await this.httpUtil.request(`192.168.xxx.xxx/readers/userinfo`, {
  4. method: http.RequestMethod.GET,
  5. extraData: { no: jwt },
  6. });
  7. let data = JSON.parse(res.result.toString());
  8. return data;
  9. } catch (error) {
  10. throw error;
  11. }
  12. }

1.2 接口数据(作为测试,可以直接使用json):

2.生命周期函数的使用--AboutToAppear AboutToDisappear

  1. aboutToAppear() {
  2. let httpRequest = http.createHttp()
  3. this.httpUtil = httpRequest
  4. // todo 初始化上一次访问时间
  5. this.getPreTime()
  6. // todo 初始化当前时间
  7. this.getLocalTimeToPreference()
  8. // todo 初始化本地数据库的密码和用户名
  9. this.getUserInfo()
  10. }

3.APPStorage进程作为缓存,只能在应用运行时使用

4.DATAPreference 数据持久化,存于用户本机

4. 分层结构

4.代码演示

1. 导入模块:
 

  1. import router from '@ohos.router' // 导入路由模块
  2. import storage from '@ohos.data.storage' // 导入数据存储模块
  3. import App from '@system.app' // 导入应用模块
  4. import Prompt from '@system.prompt' // 导入提示模块
  5. import http from '@ohos.net.http' // 导入网络请求模块
  6. import { RouterInfo } from '../../Pojo/RouterInfo' // 导入自定义的 RouterInfo 类
  7. import common from '@ohos.app.ability.common' // 导入通用模块
  8. import dataPreference from '@ohos.data.preferences' // 导入数据首选项模块

2. 定义 `Login` 结构体:
 

  1. @Entry
  2. @Component
  3. struct Login {
  4.   // 定义状态变量
  5.   @State username: string = ""
  6.   @State pwd: string = ""
  7.   @State allow: boolean = false
  8.   @State upload: boolean = true
  9.   @State uploadTag: boolean = false
  10.   @State lastLocalTime: string = ""
  11.   
  12.   // 其他属性和方法...
  13. }

3. 实例化 `RouterInfo` 对象和初始化方法:

RouterInfo是一个自定义的类

  1. export class RouterInfo{
  2. name:string
  3. url:string
  4. message:string
  5. constructor(name,url,message) {
  6. this.name=name
  7. this.url=url
  8. this.message=message
  9. }
  10. }
  1. Router = new RouterInfo("进入主页", "pages/Books/Main", "主页面")
  2. aboutToAppear() {
  3.   // 初始化操作,包括创建 HTTP 请求对象、获取上次访问时间、初始化本地时间等
  4. }

4. 页面跳转方法 `goTo()`:

  1. goTo(Router: RouterInfo) {
  2.   // 调用路由模块进行页面跳转
  3. }

5. 异步获取用户信息的方法 `jwt()`:
 

  1. async jwt(jwt: string) {
  2.   // 发起网络请求获取用户信息
  3. }

6. 存储当前时间到用户首选项方法 `getLocalTimeToPreference()`:
 

  1. // 获取当前时间并存入用户首选项
  2. getLocalTimeToPreference(){
  3. const currentDate: Date = new Date();
  4. const currentYear: number = currentDate.getFullYear();
  5. const currentMonth: number = currentDate.getMonth() + 1; // 注意:月份从 0 开始,需要加 1
  6. const currentDay: number = currentDate.getDate();
  7. const currentHour: number = currentDate.getHours();
  8. const currentMinute: number = currentDate.getMinutes();
  9. const currentSecond: number = currentDate.getSeconds();
  10. const curTime = `北京时间:${currentYear}-${currentMonth}-${currentDay} ${currentHour}:${currentMinute}:${currentSecond}`;
  11. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  12. preferences.put("curTime", curTime).then(_ => {
  13. preferences.flush();
  14. });
  15. }).catch((err: Error) => {
  16. console.error(err.message);
  17. });
  18. }

7. 获取上一次访问时间方法 `getPreTime()` 和关闭应用更新时间方法

  1. // 获取上一次的时间--lastTime
  2. getPreTime(){
  3. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  4. if (!preferences.has("lastTime")) {
  5. console.log("数据并未能保存");
  6. } else {
  7. preferences.get("lastTime", 'null').then((value) => {
  8. this.last=value.toLocaleString()
  9. // AlertDialog.show({message:`上一次访问时间:${this.last}`})
  10. console.log("数据为:" + value);
  11. }).catch(_ => {
  12. console.log("读取失败");
  13. });
  14. }
  15. });
  16. }
  17. // 关闭应用时将lastTime置换为curTime,并将curTime替换为空值
  18. closeAppAndUpdateTime(){
  19. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  20. preferences.get("curTime", '').then((curTime) => {
  21. preferences.put("lastTime", curTime);
  22. preferences.put("curTime", '');
  23. preferences.flush();
  24. console.log("上一次时间已更新,当前时间已清空");
  25. }).catch((err: Error) => {
  26. console.error(err.message)
  27. });
  28. }).catch((err: Error) => {
  29. console.error(err.message);
  30. });
  31. }

8. 用户登录方法 `login()` 和相关辅助方法:

  1. login() {
  2.   // 用户登录逻辑,包括密码验证、令牌解析、存储用户信息等操作
  3. }
  4. uploadUserInfo() {
  5.   // 将用户信息上传到本地存储
  6. }
  7. getUserInfo() {
  8.   // 获取本地存储的用户信息
  9. }

9. 构建页面布局的方法 `build()`:

  1. build() {
  2.   // 构建页面布局,包括输入框、按钮、复选框等组件
  3. }

这段代码实现了一个简单的登录页面,涵盖了用户输入、网络请求、数据存储等功能,并且使用 HarmonyOS 的一些模块来实现这些功能。

5.全代码

  1. import router from '@ohos.router'
  2. import storage from '@ohos.data.storage'
  3. import App from '@system.app'
  4. import Prompt from '@system.prompt'
  5. import http from '@ohos.net.http'
  6. import { RouterInfo } from '../../Pojo/RouterInfo'
  7. import common from '@ohos.app.ability.common'
  8. import dataPreference from '@ohos.data.preferences'
  9. @Entry
  10. @Component
  11. struct Login {
  12. // todo 定义域
  13. @State username:string=""
  14. @State pwd:string=""
  15. @State allow:boolean = false
  16. @State upload:boolean = true
  17. @State uploadTag:boolean = false
  18. @State lastLocalTime:string=""
  19. httpUtil: http.HttpRequest
  20. context = getContext(this) as common.UIAbilityContext
  21. @State last:string=''
  22. Router = new RouterInfo("进入主页","pages/Books/Main","主页面")
  23. aboutToAppear() {
  24. let httpRequest = http.createHttp()
  25. this.httpUtil = httpRequest
  26. // todo 初始化上一次访问时间
  27. this.getPreTime()
  28. // todo 初始化当前时间
  29. this.getLocalTimeToPreference()
  30. // todo 初始化本地数据库的密码和用户名
  31. this.getUserInfo()
  32. }
  33. aboutToDisappear(){
  34. // todo 保存当前时间作为上一次的时间
  35. this.closeAppAndUpdateTime()
  36. }
  37. goTo(Router:RouterInfo){
  38. router.pushUrl({
  39. url: Router.url,
  40. params:{
  41. title:Router.message
  42. }
  43. },
  44. router.RouterMode.Single,
  45. err=> {
  46. if (err) {
  47. console.log("路由失败"+err.code+':'+err.message)
  48. }
  49. })
  50. }
  51. async jwt(jwt: string) {
  52. try {
  53. const res = await this.httpUtil.request(`192.168.137.1/readers/userinfo`, {
  54. method: http.RequestMethod.GET,
  55. extraData: { no: jwt },
  56. });
  57. let data = JSON.parse(res.result.toString());
  58. return data;
  59. } catch (error) {
  60. throw error;
  61. }
  62. }
  63. // 获取当前时间并存入用户首选项
  64. getLocalTimeToPreference(){
  65. const currentDate: Date = new Date();
  66. const currentYear: number = currentDate.getFullYear();
  67. const currentMonth: number = currentDate.getMonth() + 1; // 注意:月份从 0 开始,需要加 1
  68. const currentDay: number = currentDate.getDate();
  69. const currentHour: number = currentDate.getHours();
  70. const currentMinute: number = currentDate.getMinutes();
  71. const currentSecond: number = currentDate.getSeconds();
  72. const curTime = `北京时间:${currentYear}-${currentMonth}-${currentDay} ${currentHour}:${currentMinute}:${currentSecond}`;
  73. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  74. preferences.put("curTime", curTime).then(_ => {
  75. preferences.flush();
  76. });
  77. }).catch((err: Error) => {
  78. console.error(err.message);
  79. });
  80. }
  81. // 获取上一次的时间--lastTime
  82. getPreTime(){
  83. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  84. if (!preferences.has("lastTime")) {
  85. console.log("数据并未能保存");
  86. } else {
  87. preferences.get("lastTime", 'null').then((value) => {
  88. this.last=value.toLocaleString()
  89. // AlertDialog.show({message:`上一次访问时间:${this.last}`})
  90. console.log("数据为:" + value);
  91. }).catch(_ => {
  92. console.log("读取失败");
  93. });
  94. }
  95. });
  96. }
  97. // 关闭应用时将lastTime置换为curTime,并将curTime替换为空值
  98. closeAppAndUpdateTime(){
  99. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  100. preferences.get("curTime", '').then((curTime) => {
  101. preferences.put("lastTime", curTime);
  102. preferences.put("curTime", '');
  103. preferences.flush();
  104. console.log("上一次时间已更新,当前时间已清空");
  105. }).catch((err: Error) => {
  106. console.error(err.message)
  107. });
  108. }).catch((err: Error) => {
  109. console.error(err.message);
  110. });
  111. }
  112. // todo 函数定义域
  113. async login() {
  114. if (this.username && this.pwd && this.allow) {
  115. try {
  116. const res = await this.httpUtil.request(`192.168.137.1/readers/login`, {
  117. method: http.RequestMethod.GET,
  118. extraData: { no: this.username, pwd: this.pwd },
  119. });
  120. let jsonResult = res.result.toString();
  121. let responseObject = JSON.parse(jsonResult);
  122. if (responseObject['code'] === 200) {
  123. // todo 解析令牌
  124. const data = await this.jwt(responseObject['data']);
  125. // todo 上下文 -- 存储令牌
  126. AppStorage.SetOrCreate("info",data['data']['readerno'])
  127. // todo 是否将密码存储至本地
  128. if (this.upload===true) {
  129. this.uploadUserInfo()
  130. }
  131. // todo 跳转
  132. this.goTo(this.Router)
  133. }
  134. } catch (error) {
  135. console.error(error);
  136. Prompt.showDialog({
  137. message: "登录失败",
  138. });
  139. }
  140. } else {
  141. if (!this.username || !this.pwd) {
  142. Prompt.showDialog({
  143. message: "请输入用户名和密码",
  144. });
  145. } else if (!this.allow) {
  146. Prompt.showDialog({
  147. message: "请勾选允许登录选项",
  148. });
  149. }
  150. }
  151. }
  152. uploadUserInfo(){
  153. // 用户存储信息到本地,使用用户首选项
  154. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  155. let user:{}={'username':this.username,'pwd':this.pwd}
  156. preferences.put("userInfo",JSON.stringify(user)).then(_ => {
  157. preferences.flush();
  158. });
  159. }).catch((err: Error) => {
  160. console.error(err.message);
  161. });
  162. }
  163. getUserInfo(){
  164. dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  165. preferences.get("userInfo", '').then((userInfo) => {
  166. let user = JSON.parse(userInfo.toLocaleString())
  167. if (user) {
  168. this.uploadTag=true
  169. this.username = user['username']
  170. this.pwd = user['pwd']
  171. }
  172. }).catch((err: Error) => {
  173. console.error(err.message)
  174. });
  175. }).catch((err: Error) => {
  176. console.error(err.message);
  177. });
  178. }
  179. build() {
  180. Column(){
  181. Column() {
  182. Text("掌上书店")
  183. .fontColor('#096789')
  184. .fontSize(70)
  185. this.displayLast("上一次访问时间:"+this.last)
  186. if (this.uploadTag===true){
  187. this.displayLast("本地已经存储密码")
  188. }
  189. }.margin({ bottom: 100 })
  190. .height('50%')
  191. .justifyContent(FlexAlign.Center)
  192. Column()
  193. {
  194. Row()
  195. {
  196. // 用户名输入框
  197. TextInput({ placeholder: this.username===''? "请输入您的用户名":this.username })
  198. .type(InputType.Normal)
  199. .width('80%')
  200. .height(50)
  201. .placeholderColor(Color.Black)
  202. .backgroundColor('#ffd3d7d3')
  203. .borderRadius(10)
  204. .margin({ bottom: 10})
  205. .onChange(val=>{
  206. this.username=val
  207. console.log(val)
  208. })
  209. }
  210. Row()
  211. {
  212. // 密码输入框
  213. TextInput({ placeholder: this.pwd===''?"请输入您的密码":this.pwd })
  214. .type(InputType.Password)
  215. .width('80%')
  216. .height(50)
  217. .placeholderColor(Color.Black)
  218. .backgroundColor('#ffd3d7d3')
  219. .borderRadius(10)
  220. .onChange(val=>{
  221. this.pwd=val
  222. console.log(val)
  223. })
  224. }
  225. Row(){
  226. Row(){
  227. Checkbox().onChange((val:boolean)=>{
  228. this.upload=val
  229. console.log('Checkbox2 change is'+val)
  230. })
  231. Text("将密码存储到本地")
  232. }.width('98%')
  233. .padding({left:30})
  234. .height('40')
  235. }.margin({ bottom: 40 })
  236. Row()
  237. {
  238. //登录按钮
  239. Button("登录")
  240. .width(120)
  241. .height(40)
  242. .fontColor(Color.White)
  243. .onClick(() => {
  244. this.login()
  245. })
  246. .backgroundColor('#ff5eb35b')
  247. .margin({right:40})
  248. .borderStyle(BorderStyle.Dotted)
  249. // 注册按钮
  250. Button("注册")
  251. .width(120)
  252. .height(40)
  253. .fontColor(Color.White)
  254. .onClick(() => {
  255. router.pushUrl({
  256. url: "pages/Second"
  257. })
  258. })
  259. .backgroundColor('#ff5eb35b')
  260. }
  261. .justifyContent(FlexAlign.SpaceEvenly)
  262. }
  263. .width("100%")
  264. .height("30%")
  265. Row(){
  266. Checkbox().onChange((val:boolean)=>{
  267. this.allow=val
  268. console.log('Checkbox2 change is'+val)
  269. })
  270. Text("点击代表同意相关使用条例与请求")
  271. }.width('90%')
  272. .padding({left:30})
  273. .height('40')
  274. }
  275. .height('100%')
  276. .width('100%')
  277. .margin({bottom:20})
  278. .linearGradient({
  279. direction:GradientDirection.RightBottom,
  280. colors:[[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]
  281. })
  282. }
  283. @Builder displayLast(message) {
  284. Row(){
  285. Text(message)
  286. .fontColor("b#ffe7eae7")
  287. }.width("70%").
  288. height("40")
  289. .backgroundColor("#ffe7eae7")
  290. .borderRadius(20)
  291. .padding({left:10})
  292. .margin({bottom:5})
  293. }
  294. }

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

闽ICP备14008679号