DEV Community

Cover image for Harmonyos Development : Developing HarmonyOS Applications with ArkTS: Implementation of the Login Page
liu yang
liu yang

Posted on • Edited on

Harmonyos Development : Developing HarmonyOS Applications with ArkTS: Implementation of the Login Page

🌟 Developing HarmonyOS applications with ArkTS: Implementation of the login page

When developing HarmonyOS applications, the login page is a common functional module. Through the login page, users can verify their identities and enter the main interface of the application. The following is a complete implementation of the login page, including the user entering the account and password, calling the back-end interface to verify the login information, and using local storage to save the login status.

Code Analysis

Import the module

import { router } from '@kit.ArkUI';

import { httpRequestGet } from '.. /Utils/HttpUtils';

import { LoginModel, LoginModelUser } from '.. /model/LoginModel';

import promptAction from '@ohos.promptAction';

import { common } from '@kit.AbilityKit';

import { preferences } from '@kit.ArkData';

Multiple modules have been imported to implement functions such as routing and jumping, HTTP requests, prompt boxes, and local storage.

  1. Data persistence

let dataPreference: preferences.Preferences | null = null;

A global variable dataPreference is defined to store user login information.

  1. Define the login page component

@Entry

@Component

struct Index {

@State message: string = 'Hello World';

@State username: string = "";

@State password: string = "";

private backtime: number = 0;

Private loginurl: string = "http://42.192.45.45:8080/boss/user/validlogin?" ;

A login page component named Index has been defined.

The @State decorator is used to define username and password, which are used to store the account and password entered by the user.

The loginurl is defined to store the URL of the login interface.

  1. Login logic

async toLogin() {

let username = 'username=';

let password = '&password=';

let networkurl = this.loginurl + username + this.username + password + this.password;

console.log("networkurl===>" + networkurl);

await httpRequestGet(networkurl).then((data) => {

console.log(" Login returns data: "+ data.toString());

let loginModel: LoginModel = JSON.parse(data.toString());

let msg = loginModel.msg;

let options: preferences.Options = { name: 'myStore' };

dataPreference = preferences.getPreferencesSync(getContext(), options);

if (loginModel.code == 200) {

router.pushUrl({

url: "pages/Home"

});

dataPreference.putSync("username", this.username);

dataPreference.putSync("password", this.password);

dataPreference.flush();

} else {

promptAction.showToast({

message: msg

});

}

});

}

The toLogin method was defined for handling the user login logic.

Concatenate the URL of the login interface, including the account and password entered by the user.

Send a GET request to the backend interface using httpRequestGet.

If the login is successful (the return code is 200), redirect the user to the home page and save the username and password to the local storage.

If the login fails, a prompt message will be displayed.

  1. Page Layout

build() {

Column() {

Image($r('app.media.icon2'))

.width(100)

.height(100)

.borderRadius(10)

.margin({ top: 140 })

Text(" Login Interface ")

.fontSize(24)

.fontWeight(700)

.margin({ top: 10 })

"Log in to your account to use more services"

.fontColor("#ff807b7b")

.margin({ top: 10 })

TextInput({placeholder: "Please enter your account"})

.type(InputType.Normal)

.onChange((value) => {

this.username = value;

})

.newLocalFancy()

TextInput({placeholder: "Please enter password"})

.type(InputType.Password)

.onChange((value) => {

this.password = value;

})

.newLocalFancy()

Row({ space: 10 }) {

Button(" Login ").width("80%").height(40)

.onClick(() => {

this.toLogin();

console.log(" Account: "+ this.username);

console.log(" Password: "+ this.password);

}).layoutWeight(1)

Button(" Register ").width("80%").height(40)

.onClick(() => {

router.pushUrl({

url: "pages/Register"

});

}).layoutWeight(1)

}.margin({ top: 20, right: 20, left: 20 })

}

.height('100%')

.width('100%')

}

Use the Column and Row layout components to build the UI of the login page.

It contains one picture, two text prompts, two input boxes (account and password), and two buttons (login and registration).

Listen for the value changes of the input box through the onChange event and update the username and password.

When the login button is clicked, the toLogin method is called; when the registration button is clicked, it redirects to the registration page.

  1. Style Definition

@styles

newLocalFancy() {

.margin({ top: 20, left: 20, right: 20 })

}

A style method newLocalFancy was defined for setting the margin of the input box.

  1. Return key processing

onBackPress(): boolean | void {

let nowtime = Date.now();

if (nowtime - this.backtime < "1000) {"

const mContext = getContext(this) as common.UIAbilityContext;

mContext.terminateSelf();

} else {

this.backtime = nowtime;

promptAction.showToast({

message: "Press Exit Application again"

});

}

return true;

}

The onBackPress method is defined to handle the return key event.

If the user clicks the back key twice consecutively within 1 second, the application will be exited. Otherwise, a prompt message will be displayed.

8.LoginModel

export class LoginModel {

msg? : string = "";

code? : number = 0;

user? : LoginModelUser = new LoginModelUser();

token? : string = "";

}

export class LoginModelUser {

id? : number = 0;

username? : string = "";

password? : string = "";

phone? : string = "";

sex? : string = "";

}

Top comments (0)