HarmonyOS Next 实现登录注册页面(ARKTS) 并利用Springboot作为后端提供接 ...

耶耶耶耶耶  论坛元老 | 2024-6-24 08:20:16 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1649|帖子 1649|积分 4947

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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'import storage from '@ohos.data.storage'import App from '@system.app'import Prompt from '@system.prompt'import http from '@ohos.net.http'import { RouterInfo } from '../../Pojo/RouterInfo'import common from '@ohos.app.ability.common'import dataPreference from '@ohos.data.preferences'@Entry@Componentstruct Login {  // todo 界说域  @State username:string=""  @State pwd:string=""  @State allow:boolean = false  @State upload:boolean = true  @State uploadTag:boolean = false  @State lastLocalTime:string=""  httpUtil: http.HttpRequest  context = getContext(this) as common.UIAbilityContext  @State last:string=''  Router = new RouterInfo("进入主页","pages/Books/Main","主页面")  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.   }
  11.   aboutToDisappear(){    // todo 生存当前时间作为上一次的时间    this.closeAppAndUpdateTime()  }  goTo(Router:RouterInfo){    router.pushUrl({      url: Router.url,      params:{        title:Router.message      }    },      router.RouterMode.Single,      err=> {        if (err) {          console.log("路由失败"+err.code+':'+err.message)        }      })  }  async jwt(jwt: string) {    try {      const res = await this.httpUtil.request(`192.168.137.1/readers/userinfo`, {        method: http.RequestMethod.GET,        extraData: { no: jwt },      });      let data = JSON.parse(res.result.toString());      return data;    } catch (error) {      throw error;    }  }  // 获取当前时间并存入用户首选项
  12.   getLocalTimeToPreference(){
  13.     const currentDate: Date = new Date();
  14.     const currentYear: number = currentDate.getFullYear();
  15.     const currentMonth: number = currentDate.getMonth() + 1; // 注意:月份从 0 开始,需要加 1
  16.     const currentDay: number = currentDate.getDate();
  17.     const currentHour: number = currentDate.getHours();
  18.     const currentMinute: number = currentDate.getMinutes();
  19.     const currentSecond: number = currentDate.getSeconds();
  20.     const curTime = `北京时间:${currentYear}-${currentMonth}-${currentDay} ${currentHour}:${currentMinute}:${currentSecond}`;
  21.     dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  22.       preferences.put("curTime", curTime).then(_ => {
  23.         preferences.flush();
  24.       });
  25.     }).catch((err: Error) => {
  26.       console.error(err.message);
  27.     });
  28.   }  // 获取上一次的时间--lastTime
  29.   getPreTime(){
  30.     dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  31.       if (!preferences.has("lastTime")) {
  32.         console.log("数据并未能保存");
  33.       } else {
  34.         preferences.get("lastTime", 'null').then((value) => {
  35.           this.last=value.toLocaleString()
  36.           // AlertDialog.show({message:`上一次访问时间:${this.last}`})
  37.           console.log("数据为:" + value);
  38.         }).catch(_ => {
  39.           console.log("读取失败");
  40.         });
  41.       }
  42.     });
  43.   }
  44.   // 关闭应用时将lastTime置换为curTime,并将curTime替换为空值
  45.   closeAppAndUpdateTime(){
  46.     dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {
  47.       preferences.get("curTime", '').then((curTime) => {
  48.         preferences.put("lastTime", curTime);
  49.         preferences.put("curTime", '');
  50.         preferences.flush();
  51.         console.log("上一次时间已更新,当前时间已清空");
  52.       }).catch((err: Error) => {
  53.         console.error(err.message)
  54.       });
  55.     }).catch((err: Error) => {
  56.       console.error(err.message);
  57.     });
  58.   }
  59.   // todo 函数界说域  async login() {    if (this.username && this.pwd && this.allow) {      try {        const res = await this.httpUtil.request(`192.168.137.1/readers/login`, {          method: http.RequestMethod.GET,          extraData: { no: this.username, pwd: this.pwd },        });        let jsonResult = res.result.toString();        let responseObject = JSON.parse(jsonResult);        if (responseObject['code'] === 200) {          // todo 解析令牌          const data = await this.jwt(responseObject['data']);          // todo 上下文 -- 存储令牌          AppStorage.SetOrCreate("info",data['data']['readerno'])          // todo 是否将密码存储至当地          if (this.upload===true) {            this.uploadUserInfo()          }          // todo 跳转          this.goTo(this.Router)        }      } catch (error) {        console.error(error);        Prompt.showDialog({          message: "登录失败",        });      }    } else {      if (!this.username || !this.pwd) {        Prompt.showDialog({          message: "请输入用户名和密码",        });      } else if (!this.allow) {        Prompt.showDialog({          message: "请勾选允许登录选项",        });      }    }  }  uploadUserInfo(){    // 用户存储信息到当地,利用用户首选项    dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {      let user:{}={'username':this.username,'pwd':this.pwd}      preferences.put("userInfo",JSON.stringify(user)).then(_ => {        preferences.flush();      });    }).catch((err: Error) => {      console.error(err.message);    });  }  getUserInfo(){    dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {      preferences.get("userInfo", '').then((userInfo) => {        let user = JSON.parse(userInfo.toLocaleString())        if (user) {          this.uploadTag=true          this.username = user['username']          this.pwd = user['pwd']        }      }).catch((err: Error) => {        console.error(err.message)      });    }).catch((err: Error) => {      console.error(err.message);    });  }  build() {      Column(){        Column() {            Text("掌上书店")              .fontColor('#096789')              .fontSize(70)          this.displayLast("上一次访问时间:"+this.last)          if (this.uploadTag===true){            this.displayLast("当地已经存储密码")          }        }.margin({ bottom: 100 })        .height('50%')        .justifyContent(FlexAlign.Center)        Column()        {          Row()          {            // 用户名输入框            TextInput({ placeholder: this.username===''? "请输入您的用户名":this.username })              .type(InputType.Normal)              .width('80%')              .height(50)              .placeholderColor(Color.Black)              .backgroundColor('#ffd3d7d3')              .borderRadius(10)              .margin({ bottom: 10})              .onChange(val=>{                this.username=val                console.log(val)              })          }          Row()          {            // 密码输入框            TextInput({ placeholder: this.pwd===''?"请输入您的密码":this.pwd })              .type(InputType.Password)              .width('80%')              .height(50)              .placeholderColor(Color.Black)              .backgroundColor('#ffd3d7d3')              .borderRadius(10)              .onChange(val=>{                this.pwd=val                console.log(val)              })          }          Row(){            Row(){              Checkbox().onChange((val:boolean)=>{                this.upload=val                console.log('Checkbox2 change is'+val)              })              Text("将密码存储到当地")            }.width('98%')            .padding({left:30})            .height('40')          }.margin({ bottom: 40 })          Row()          {            //登录按钮            Button("登录")              .width(120)              .height(40)              .fontColor(Color.White)              .onClick(() => {                this.login()              })              .backgroundColor('#ff5eb35b')              .margin({right:40})              .borderStyle(BorderStyle.Dotted)            //  注册按钮            Button("注册")              .width(120)              .height(40)              .fontColor(Color.White)              .onClick(() => {                router.pushUrl({                  url: "pages/Second"                })              })              .backgroundColor('#ff5eb35b')          }          .justifyContent(FlexAlign.SpaceEvenly)        }        .width("100%")        .height("30%")        Row(){          Checkbox().onChange((val:boolean)=>{            this.allow=val            console.log('Checkbox2 change is'+val)          })          Text("点击代表同意相关利用条例与请求")        }.width('90%')        .padding({left:30})        .height('40')      }      .height('100%')        .width('100%')        .margin({bottom:20})        .linearGradient({          direction:GradientDirection.RightBottom,          colors:[[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]        })  }  @Builder displayLast(message) {    Row(){      Text(message)        .fontColor("b#ffe7eae7")    }.width("70%").    height("40")    .backgroundColor("#ffe7eae7")    .borderRadius(20)    .padding({left:10})    .margin({bottom:5})  }}
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

耶耶耶耶耶

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表