目录
2.采用ArkTs 的 AppStorage保存一个全局的用户信息
1.要想获取用户信息的值,必须在登录成功之后用AppStorage.SetOrCreate()保存用户信息全局变量
2.1 因为初始化了一个username为‘test’的用户信息,所以,通过判断username的值来判断是否未登录状态,如果为登录状态则显示个人信息,未登录,则显示"未登录"按钮。
2.2 通过AppStorage.Get方法获取用户信息全局变量的值
前言
1.通过用户登录请求接口,获取用户信息
2.采用ArkTs 的 AppStorage保存一个全局的用户信息
3.实现用户信息的取值
1.要想获取用户信息的值,必须在登录成功之后用AppStorage.SetOrCreate()保存用户信息全局变量
import router from "@ohos.router"
import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction';
import postReqeust from '../utils/HttpUtil';
export class UserInfo{
id:number;
username:String;
realName:String;
email:String;
qq:String;
phone:String;
constructor(id: number,
username: string,
realName: string,
email: String,
qq: String,
phone: String
) {
this.id = id;
this.username = username;
this.realName = realName;
this.email = email;
this.qq = qq;
this.phone = phone;
}
}
//构建用户信息数据
let userInfo: UserInfo = new UserInfo(1,'test','游客','','','123456xxxxx');
//保存用户对象伟键值对
// let para: Record<string, UserInfo> = { 'userInfo': userInfo };
@Entry
@Component
struct Index{
@State userInfo:UserInfo=null;
//定义用户名
@State username:string ="";
//定义密码
@State password:string ="";
//定义重复用户名密码
@State repeatPwd:string ="";
//判断是否为空的标志
@State isBlank:boolean=false;
//提示语
@State message:string ="";
//全局URL
@State URL:string ="http://127.0.0.1:8083";
//定义颜色的值
// @ts-ignore
@State colorParm:Color = Color.Gray;
//判断输入的参数是否为空方法
isEmty(username:string,password:string,repeatPwd:string){
//判断用户名是否为空
if(username==null ||username==""){
console.debug("用户名为空----");
return true;
}
if(password==null ||password==""){
console.debug("密码为空----");
return true;
}
if(repeatPwd==null ||repeatPwd==""){
console.debug("重复输入密码为空----");
return true;
}
}
//创建请求的方法
postReq(){
//创建http请求
var httpReq = http.createHttp();
console.info("发起请求----")
httpReq.request("http://ntek44b.nat.ipyingshe.com/login",{
//定义请求方法
method:http.RequestMethod.POST,
//添加请求头
header:{
'Content-Type':'application/json',
'charset':'utf-8'
},
//请求数据,用户名,密码
extraData:{
"username":this.username,
"password":this.password,
},
connectTimeout:60000,
readTimeout:72000,
},(msg,data)=>{
//请求成功
if (msg.code==200){
this.colorParm = Color.Green;
this.message ="登录成功!";
}else {
// @ts-ignore
this.colorParm = Color.Red;
this.message ="登录失败,请检查用户名或密码";
}
}
);
}
build() {
//垂直的容器
Column({ space: 5 }) {
Row({space:2}){
Image($r("app.media.app_icon"))
.width("100")
.height("100")
.margin(50);
}
Column({ space: 5 }) {
//输入框
TextInput({ placeholder: "请输入用户名" }).type(InputType.Normal)
.width("300").onChange((username: string) => {
//通过onChange事件获取用户名
this.username = username;
console.debug("username==={}", this.username);
});
//密码输入框
TextInput({ placeholder: "请输入密码" }).type(InputType.Password)
.width("300").onChange((password: string) => {
//通过onChange事件获取密码
this.password = password;
console.debug("password==={}", this.password);
});
//重新确认密码
TextInput({ placeholder: "请再次输入密码" }).type(InputType.Password)
.width("300").onChange((repeatPwd: string) => {
//通过onChange事件获取重复输入的密码
this.repeatPwd = repeatPwd;
console.debug("repeatPwd==={}", this.repeatPwd);
});
Row({ space: 5 }) {
Text("提示语:").fontColor(Color.Gray);
// @ts-ignore
Text(this.message).fontColor(this.colorParm);
}
Row({space:2}) {
//登录
Button("登录").width("20%").onClick(async () => {
//判断是否为空
this.isBlank = this.isEmty(this.username, this.password, this.repeatPwd);
if (this.isBlank) {
this.colorParm = Color.Red;
this.message = "请检查参数是否为空";
return;
} else {
//判断两次输入的密码是否正确
if (this.password != this.repeatPwd) {
this.colorParm = Color.Red;
this.message = "两次输入的密码不一致";
return;
}
}
//网络请求数据库验证登录
//发送异步请求
postReqeust("http://r3y8xeo.nat.ipyingshe.com/login", this.username, this.password)
.then(data => {
// 处理成功的数据
if (data.responseCode===200) {
// @ts-ignore
userInfo = JSON.parse(data.result).data as UserInfo;
AppStorage.SetOrCreate('userInfo', userInfo);
//成功弹窗
promptAction.showToast({
// @ts-ignore
message: JSON.parse(data.result).msg
});
router.pushUrl({ url: 'pages/shouye'}).then(() => {
}).catch((err) => {
});
}else {
promptAction.showToast({
message: '账号或者密码错误!' // 弹窗内容
});
}
})
.catch(error => {
promptAction.showToast({
message: '请求失败,网络接口有问题!' // 弹窗内容
});
});
}).backgroundColor(Color.Green);
Button("注册").onClick(() => {
// 跳转到第二页
router.pushUrl({ url: 'pages/Register'}).then(() => {
}).catch((err) => {
});
});
}
}.height("100%")
.width("100%")
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
}
1.1 构建用户类
export class UserInfo{
id:number;
username:String;
realName:String;
email:String;
qq:String;
phone:String;
constructor(id: number,
username: string,
realName: string,
email: String,
qq: String,
phone: String
) {
this.id = id;
this.username = username;
this.realName = realName;
this.email = email;
this.qq = qq;
this.phone = phone;
}
}
2.2 初始化用户信息
//构建用户信息数据
let userInfo: UserInfo = new UserInfo(1,'test','游客','','','123456xxxxx');
2.3 保存用户信息
userInfo = JSON.parse(data.result).data as UserInfo;
AppStorage.SetOrCreate('userInfo', userInfo);
2.用户信息界面设置布局
import router from "@ohos.router"
import {UserInfo} from "../pages/Index"
let userLocalStorage = AppStorage.Get<UserInfo>('userInfo') // == 49
@Entry
@Component
export struct avator{
@State isLogin:boolean = userLocalStorage.username !='test';
build() {
Row() {
Image($r('app.media.avator'))
.width(80)
.height(80)
.margin({ right: 20 })
if (this.isLogin){
Column() {
// @ts-ignore
Text(userLocalStorage.username)
.fontSize(20)
.margin({ bottom: 8 })
Text('姓名:'+userLocalStorage.realName)
.fontSize(16)
.fontColor(Color.Gray)
.margin({ bottom: 8 })
} .alignItems(HorizontalAlign.Start)
.width('80%')
.height('100%')
}else {
Button('未登录').backgroundColor(Color.Yellow).onClick(()=>{
router.pushUrl({ url: 'pages/Index'}).then(() => {
}).catch((err) => {
});
})
}
}
.padding(20)
.borderRadius(12)
.backgroundColor('#FFECECEC')
.height(120)
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
}
2.1 因为初始化了一个username为‘test’的用户信息,所以,通过判断username的值来判断是否未登录状态,如果为登录状态则显示个人信息,未登录,则显示"未登录"按钮。
@State isLogin:boolean = userLocalStorage.username !='test';
2.2 通过AppStorage.Get方法获取用户信息全局变量的值
let userLocalStorage = AppStorage.Get<UserInfo>('userInfo')
3.个人信息展示效果
4.数据库数据
鸿蒙代码和后端请求代码附在博文资源,有需要可自取。