ITPub博客

首页 > 移动开发 > HTML5 > 《仿盒马》app开发技术分享-- 用户登录页(业务逻辑)(21)

《仿盒马》app开发技术分享-- 用户登录页(业务逻辑)(21)

原创 HTML5 作者:鸿蒙小林 时间:2025-06-26 20:19:10 0 删除 编辑


## 技术栈


Appgallery connect

## 开发准备


上一节我们实现了静态的用户登录页,这一节我们需要给他添加上业务逻辑,实现跟云数据库的互通,同时跟整个应用关联起来,因为我们还没有实现用户的注册页面,所以这里我们在云数据库的用户数据插入暂时先不做同用户名的校验,我们在云端先插入几条数据,暂时专注于查询即可


## 功能分析


登录页的业务逻辑主要还是针对用户输入的账号密码跟数据库存储的信息是否匹配,用户登录成功之后对当前信息的存储和使用。


## 代码实现


首先我们来创建用户表

{

  "objectTypeName": "user",

  "fields": [

    {"fieldName": "id", "fieldType": "Integer", "notNull": true, "belongPrimaryKey": true},

    {"fieldName": "user_id", "fieldType": "Integer", "notNull": true, "defaultValue": 0},

    {"fieldName": "user_name", "fieldType": "String"},

    {"fieldName": "psw", "fieldType": "String"},

    {"fieldName": "is_vip", "fieldType": "Boolean"},

    {"fieldName": "user_code", "fieldType": "String"},

    {"fieldName": "is_log_off", "fieldType": "Boolean"}

  ],

  "indexes": [

    {"indexName": "field1IndexId", "indexList": [{"fieldName":"id","sortType":"ASC"}]}

  ],

  "permissions": [

    {"role": "World", "rights": ["Read", "Upsert", "Delete"]},

    {"role": "Authenticated", "rights": ["Read", "Upsert", "Delete"]},

    {"role": "Creator", "rights": ["Read", "Upsert", "Delete"]},

    {"role": "Administrator", "rights": ["Read", "Upsert", "Delete"]}

  ]

}

关键的参数有账号密码,以及用户id 、是否注销,这些参数我们在其他查询中使用会比较多

创建表之后生成对应的db类和实体类



class User {

    id: number;

    user_id: number = 0;

    user_name: string;

    psw: string;

    is_vip: boolean;

    user_code: string;

    is_log_off: boolean;


    constructor() {

    }



    setId(id: number): void {

        this.id = id;

    }


    getId(): number  {

        return this.id;

    }


    setUser_id(user_id: number): void {

        this.user_id = user_id;

    }


    getUser_id(): number  {

        return this.user_id;

    }


    setUser_name(user_name: string): void {

        this.user_name = user_name;

    }


    getUser_name(): string  {

        return this.user_name;

    }


    setPsw(psw: string): void {

        this.psw = psw;

    }


    getPsw(): string  {

        return this.psw;

    }


    setIs_vip(is_vip: boolean): void {

        this.is_vip = is_vip;

    }


    getIs_vip(): boolean  {

        return this.is_vip;

    }


    setUser_code(user_code: string): void {

        this.user_code = user_code;

    }


    getUser_code(): string  {

        return this.user_code;

    }


    setIs_log_off(is_log_off: boolean): void {

        this.is_log_off = is_log_off;

    }


    getIs_log_off(): boolean  {

        return this.is_log_off;

    }


    static parseFrom(inputObject: any): User {

        let result = new User();

        if (!inputObject) {

            return result;

        }

        if (inputObject.id) {

            result.id = inputObject.id;

        }

        if (inputObject.user_id) {

            result.user_id = inputObject.user_id;

        }

        if (inputObject.user_name) {

            result.user_name = inputObject.user_name;

        }

        if (inputObject.psw) {

            result.psw = inputObject.psw;

        }

        if (inputObject.is_vip) {

            result.is_vip = inputObject.is_vip;

        }

        if (inputObject.user_code) {

            result.user_code = inputObject.user_code;

        }

        if (inputObject.is_log_off) {

            result.is_log_off = inputObject.is_log_off;

        }

        return result;

    }

}


export { User };



import { cloudDatabase } from '@kit.CloudFoundationKit';


class user extends cloudDatabase.DatabaseObject {

  public id: number;

  public user_id = 0;

  public user_name: string;

  public psw: string;

  public is_vip: boolean;

  public user_code: string;

  public is_log_off: boolean;


  public naturalbase_ClassName(): string {

    return 'user';

  }

}


export { user };


全部创建完成之后我们还需要添加一个工具类,我们封装一个用户首选项相关,帮助我们存储数据


import dataPreferences from '@ohos.data.preferences';

import common from '@ohos.app.ability.common';

let context = getContext(this) as common.UIAbilityContext;

/**

 * 项目全局存储,使用ohos.data.preferences

 */

const defaultPreferenceName = "OPEN_EYE_PREFERENCES"


type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;



/**

 * 轻量级缓存工具类

 */

let promise = dataPreferences.getPreferences(context, defaultPreferenceName);


export class StorageUtils {


  static async getAwait(name:string, def = 'moren'): Promise<string> {

    return await new Promise((resolve: Function) => {

      promise.then((res) => {

        res.get(name, def)

          .then((data: dataPreferences.ValueType) => {

            resolve(data.toString());

          })

      })

    });

  }

  static async getAwaitBoolen(name:string, def = false): Promise<boolean> {

    return await new Promise((resolve: Function) => {

      promise.then((res) => {

        res.get(name, def)

          .then((data: dataPreferences.ValueType) => {

            resolve(data);

          })

      })

    });

  }


  static getCallBack<T extends dataPreferences.ValueType>(name:string,

                                                          callBack: (t:T) => void,

                                                          def = 'moren') {

    promise.then((res) => {

      res.get(name, def)

        .then((data: dataPreferences.ValueType) => {

          callBack(data  as T )

        })

    })

  }

  // static async getAll(name:string): Promise<string> {

  //   return await new Promise((resolve: Function) => {

  //     promise.then((res) => {

  //       res.getSync(name,'')

  //     })

  //   });

  // }

  static async getAll(name:string): Promise<string> {

    return await new Promise((resolve: Function) => {

      promise.then((res) => {

        res.get(name,"")

          .then((data: dataPreferences.ValueType) => {

            resolve(data);

          })

      })

    });


  }



  /**

   *

   * @param name 传入的key

   * @param valuer 传入的 value

   * 传入需要储存的字段

   */

  static set(name:string, valuer:string): void {

    promise.then((res) => {

      res.put(name, valuer)

      res.flush()

    })

  }

  static remove(name:string): void {

    promise.then((res) => {

      res.delete(name)

    })

  }

  static clear(): void {

    promise.then((res) => {

      res.clear()

    })

  }

  static async has(name:string): Promise<boolean> {

    return await new Promise((resolve: Function) => {

      promise.then((res) => {

        res.has(name)

          .then((data: dataPreferences.ValueType) => {

            resolve(data);

          })

      })

    });


  }

}

现在我们可以完善相关的业务逻辑了,我们需要处理的有,数据的查询,状态的判断,根据是否注销,是否有对应的账号密码,来执行对应的逻辑


async login(): Promise<void>{

    if (this.acc===''&&this.psw==='') {

      promptAction.showToast({message:"请输入账号或密码"})

      return

    }else {

      let condition = new cloudDatabase.DatabaseQuery(user);

      condition.equalTo("user_name",this.acc).and().equalTo("psw",this.psw)

      let listData = await databaseZone.query(condition);


      let json = JSON.stringify(listData)

      let data1:User[]= JSON.parse(json)

      if (data1.length>0) {

        if (data1[0].is_log_off) {

          //已经注销

          promptAction.showDialog({

            title: '提示',

            message: '改账号已经注销',

            buttons: [

              {

                text: '去处理',

                color: '#ffffff'

              },

              {

                text: '关闭',

                color: '#ffffff'

              }

            ],

          })

            .then(data => {

              showToast(data.index+"")

              console.info('showDialog success, click button: ' + data.index);

            })

            .catch((err: Error) => {

              console.info('showDialog error: ' + err);

            })

        }else {

          //未注销

          StorageUtils.set("user_id",data1[0].user_id.toString())

          router.back()

        }

        

        

      }else {

        showToast("请检查用户名或密码")

      }

      hilog.info(0x0000, 'testTag', `Succeeded in querying data, result: ${data1}`);

    }

  }

到这里我们就实现了相关的业务逻辑,登录页的业务逻辑就实现了


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70046889/viewspace-3089103/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2025-06-26

  • 博文量
    90
  • 访问量
    67475