当前位置: 首页 > article >正文

鸿蒙特色实战2

服务卡片开发

创建服务卡片

创建一个新的工程后,可以通过如下方法进行创建服务卡片:

  1. 创建服务卡片包括如下两种方式:

    • 选择模块(如entry模块)下的任意文件,单击菜单栏File > New > Service Widget创建服务卡片。
    • 选择模块(如entry模块)下的任意文件,单击右键 > New > Service Widget创建服务卡片。
  2. Choose a Template for Your Service Widget界面中,选择卡片模板,单击Next

在这里插入图片描述

  1. Configure Your Service Widget界面中,配置卡片的基本信息,包括:

  2. 单击Finish完成卡片的创建。创建完成后,工具会自动创建出服务卡片的布局文件,并在form_config.json文件中写入服务卡片的属性字段,关于各字段的说明请参考配置文件说明。

    在这里插入图片描述

  3. 卡片创建完成后,请根据开发指导,完成服务卡片的开发,详情请参考服务卡片开发指南。

  4. 本项目开发两个卡片,分别为 2X2 和 4X4卡片,2X2卡片为一张Logo图片,4X4卡片为新闻列表。如图:

    2X2卡片4X4卡片
    在这里插入图片描述

|在这里插入图片描述|

2X2卡片开发

2X2卡片比较简单,就是一张Logo图片,点击跳转到主界面,全部代码以下:

@Entry
@Component
struct WidgetCard {

  readonly ACTION_TYPE: string = 'router';
  readonly ABILITY_NAME: string = 'EntryAbility';
  readonly FULL_WIDTH_PERCENT: string = '100%';
  readonly FULL_HEIGHT_PERCENT: string = '100%';

  build() {
    Stack() {
        // Logo图片
      Image($r("app.media.startIcon"))
        .width(this.FULL_WIDTH_PERCENT)
        .height(this.FULL_HEIGHT_PERCENT)
        .objectFit(ImageFit.Contain)
    }
    .width(this.FULL_WIDTH_PERCENT)
    .height(this.FULL_HEIGHT_PERCENT)
    .onClick(() => {
        // 点击跳转到主界面
      postCardAction(this, {
        action: this.ACTION_TYPE,
        abilityName: this.ABILITY_NAME
      });
    })
  }
}

4X4卡片开发

4X4卡片相对复杂些,获取网络上新闻列表数组,循环数据显示出现,点击每条新闻,把新闻Id传过去,获取相应的详情新闻。

  1. 卡片页面布局代码:

    Column() {
          Row() {
            Row() {
              Text('Days Matter')
                .fontColor(0xF55A42)
                .fontWeight(700)
                .fontSize(18)
            }
            .height(40)
            .justifyContent(FlexAlign.Start)
    
            Text('更多 >')
              .width(64)
              .height("100%")
              .textAlign(TextAlign.End)
              .onClick(() => {
                console.info(`xx 跳转到更多`)
                postCardAction(this, {
                  action: this.ACTION_TYPE,
                  abilityName: this.ABILITY_NAME,
                  params: {
                    'id': '-1',
                    'targetPage': 'Index'
                  }
                });
              })
          }
          .width("100%")
          .height(40)
          .justifyContent(FlexAlign.SpaceBetween)
    
          List({ space: 20, initialIndex: 0 }) {
            ForEach(this.newsArticles, (item:object) => {
              ListItem() {
                Text(item['title'])
                  .width("100%")
                  .height(20)
                  .fontSize(14)
                  .padding({ left: 10, right: 10})
                  .textOverflow({ overflow: TextOverflow.Ellipsis })
                  .fontWeight(FontWeight.Regular)
                  .maxLines(this.MAX_LINES)
              }
              .onClick(() => {
                this.routerPage(item['id'])
              })
            })
          }
          .listDirection(Axis.Vertical)
          .divider({ strokeWidth: 1, color: "#E4EBF5", startMargin: 10, endMargin: 10 })
          .edgeEffect(EdgeEffect.Spring)
          .margin({ top: 4 })
          .padding( { bottom: 40 })
    
        }
        .width("100%")
        .height("100%")
        .justifyContent(FlexAlign.Start)
        .alignItems(HorizontalAlign.Start)
        .padding($r('app.float.column_padding'))
    
  2. 路由跳转代码:

      routerPage(uid: string) {
        console.info(`xx 跳转文章Id: ${uid}`)
        postCardAction(this, {
          action: this.ACTION_TYPE,
          abilityName: this.ABILITY_NAME,
          params: {
            'id': uid,
            'targetPage': 'Detail'
          }
        });
      }
    
  3. 卡片页面中使用LocalStorageProp装饰需要刷新的卡片数据

    let storageCard = new LocalStorage();
    
    @Entry(storageCard)
    @Component
    struct Widget4Card {
    
      @LocalStorageProp('newsArticles') newsArticles: Array<object> = [];
        ......
    }
    
  4. 4x4服务卡片完整代码如下:

    let storageCard = new LocalStorage();
    
    @Entry(storageCard)
    @Component
    struct Widget4Card {
    
      @LocalStorageProp('newsArticles') newsArticles: Array<object> = [];
    
      readonly MAX_LINES: number = 1;
      readonly ACTION_TYPE: string = 'router';
      readonly ABILITY_NAME: string = 'EntryAbility';
    
      routerPage(uid: string) {
        console.info(`xx 跳转文章Id: ${uid}`)
        postCardAction(this, {
          action: this.ACTION_TYPE,
          abilityName: this.ABILITY_NAME,
          params: {
            'id': uid,
            'targetPage': 'Detail'
          }
        });
      }
    
      build() {
        Column() {
          Row() {
            Row() {
              Text('Days Matter')
                .fontColor(0xF55A42)
                .fontWeight(700)
                .fontSize(18)
            }
            .height(40)
            .justifyContent(FlexAlign.Start)
    
            Text('更多 >')
              .width(64)
              .height("100%")
              .textAlign(TextAlign.End)
              .onClick(() => {
                console.info(`xx 跳转到更多`)
                postCardAction(this, {
                  action: this.ACTION_TYPE,
                  abilityName: this.ABILITY_NAME,
                  params: {
                    'id': '-1',
                    'targetPage': 'Index'
                  }
                });
              })
          }
          .width("100%")
          .height(40)
          .justifyContent(FlexAlign.SpaceBetween)
    
          List({ space: 20, initialIndex: 0 }) {
            ForEach(this.newsArticles, (item:object) => {
              ListItem() {
                Text(item['title'])
                  .width("100%")
                  .height(20)
                  .fontSize(14)
                  .padding({ left: 10, right: 10})
                  .textOverflow({ overflow: TextOverflow.Ellipsis })
                  .fontWeight(FontWeight.Regular)
                  .maxLines(this.MAX_LINES)
              }
              .onClick(() => {
                this.routerPage(item['id'])
              })
            })
          }
          .listDirection(Axis.Vertical)
          .divider({ strokeWidth: 1, color: "#E4EBF5", startMargin: 10, endMargin: 10 })
          .edgeEffect(EdgeEffect.Spring)
          .margin({ top: 4 })
          .padding( { bottom: 40 })
    
        }
        .width("100%")
        .height("100%")
        .justifyContent(FlexAlign.Start)
        .alignItems(HorizontalAlign.Start)
        .padding($r('app.float.column_padding'))
    
      }
    }
    

卡片保存开发

  1. 根据配置文件form_config.json配置定时更新卡片数据

    "updateEnabled": true, // 表示卡片是否支持周期性刷新(包含定时刷新和定点刷新)
    "scheduledUpdateTime": "10:30",	// 表示卡片的定点刷新的时刻,采用24小时制,精确到分钟。
    "updateDuration": 1,	// 表示卡片定时刷新的更新周期,单位为30分钟,取值为自然数。
    
  2. 卡片存储

    2.1 在EntryAbility.ets里onCreate回调函数初始化存储卡片数据库和表。

    onCreate() {
            // 初始化保存卡片数据库
        RdbUtils.initDb(this.context, Const.RDB_NAME.dbName ? Const.RDB_NAME.dbName : '');
        await RdbUtils.createDb();
        RdbUtils.createTable(Const.FORM_INFO.tableName ? Const.FORM_INFO.tableName : '', columnFormInfoList)
          .catch((err: Error) => {
            LogUtil.error(`RdbHelper formInfo err : ${JSON.stringify(err)}`);
          });
    }
    

    2.2 在EntryFormAbility.ets里onAddForm回调存储添加的卡片信息

    onAddForm(want: Want) {
        LogUtil.info('xx 开始添加卡片')
        let parameters = want.parameters;
        if (parameters) {
          let formId: string = parameters[Const.FORM_PARAM_IDENTITY_KEY] as string;
          let formName: string = parameters[Const.FORM_PARAM_NAME_KEY] as string;
          let formDimension: number = parameters[Const.FORM_PARAM_DIMENSION_KEY] as number;
          let formInfo: FormInfoModel = {
            formId: formId,
            formName: formName,
            formDimension: formDimension
          };
          LogUtil.info('xx 开始卡片保存到数据库')
          FormUtils.insertFormData(this.context, formInfo);
          LogUtil.info('xx 结束卡片保存到数据库')
        }
    
        LogUtil.info('xx 卡片创建成功')
        return formBindingData.createFormBindingData({
          'latestArticles': []
        });
      }
    

    2.3 卡片周期性刷新时,调用卡片onUpdateForm更新回调

      onUpdateForm(formId: string) {
        // Called to notify the form provider to update a specified form.
        FormUtils.updateCards(this.context);
      }
    

    2.4 卡片移除时,调用卡片onRemoveForm回调

      onRemoveForm(formId: string) {
        // Called to notify the form provider that a specified form has been destroyed.
        FormUtils.deleteFormData(this.context, formId);
      }
    

卡片保存在关系型数据库

接口RdbHelper

定义一个关系型数据库操作接口RdbHelper

import dataRdb from '@ohos.data.relationalStore';
import ColumnInfo from '../model/ColumnInfo';

export interface RdbHelper {

  getDbName(): string;

  getRdb(context: Context): Promise<RdbHelper>;

  executeSql(sql: string): Promise<void>;

  createTable(tableName: string, columns: Array<ColumnInfo>): Promise<void>;

  deleteTable(tableName: string): Promise<void>;

  addTableColumn(tableName: string, column: ColumnInfo): Promise<void>;

  insert(tableName: string, values: dataRdb.ValuesBucket | Array<dataRdb.ValuesBucket>): Promise<number>;

  update(values: dataRdb.ValuesBucket, rdbPredicates: dataRdb.RdbPredicates): Promise<number>;

  query(rdbPredicates: dataRdb.RdbPredicates, columns?: Array<string>): Promise<dataRdb.ResultSet>;

  queryAll(tableName: string): Promise<dataRdb.ResultSet>;

  queryBySql(sql: string, bindArgs?: Array<dataRdb.ValueType>): Promise<dataRdb.ResultSet>;

  delete(rdbPredicates: dataRdb.RdbPredicates): Promise<number>;
}

实现类RdbHelperImp

定义一个实现RdbHelper接口的实现类RdbHelperImp

import { LogUtil } from '../../utils/LogUtil';
import { RdbHelper } from './RdbHelper';
import dataRdb from '@ohos.data.relationalStore';
import ColumnInfo from '../model/ColumnInfo';
import tableHelper from './TableHelper';

export class RdbHelperImp implements RdbHelper {
  private mDatabaseName: string;
  private rdbStore: dataRdb.RdbStore = {} as dataRdb.RdbStore;
  private storeConfig: dataRdb.StoreConfig = {  name: '', securityLevel: dataRdb.SecurityLevel.S1 } as dataRdb.StoreConfig;

  constructor(databaseName: string) {
    this.mDatabaseName = databaseName;
  }

  getDbName(): string {
    return this.mDatabaseName;
  }

  getRdb(context: Context): Promise<RdbHelper> {
    this.storeConfig = {
      name: this.mDatabaseName, securityLevel: dataRdb.SecurityLevel.S1
    };
    return new Promise<RdbHelper>((success, error) => {
      dataRdb.getRdbStore(context, this.storeConfig).then(dbStore => {
        this.rdbStore = dbStore;
        success(this);
      }).catch((err: Error) => {
        LogUtil.error(`initRdb err : ${JSON.stringify(err)}`);
        error(err);
      })
    })
  }

  executeSql(sql: string): Promise<void> {
    LogUtil.info(`executeSql sql : ${sql}`);
    return this.rdbStore.executeSql(sql);
  }

  createTable(tableName: string, columns: Array<ColumnInfo>): Promise<void> {
    LogUtil.info(`createTable tableName : ${tableName}, columns : ${JSON.stringify(columns)}`);
    let createTableSql = tableHelper.createTableSql(tableName, columns);
    return this.executeSql(createTableSql);
  }

  deleteTable(tableName: string): Promise<void> {
    LogUtil.info(`deleteTable tableName : ${tableName}`);
    let deleteTableSql = tableHelper.deleteTableSql(tableName);
    return this.executeSql(deleteTableSql);
  }

  addTableColumn(tableName: string, column: ColumnInfo): Promise<void> {
    LogUtil.info(`addTableColumn tableName : ${tableName}, column : ${JSON.stringify(column)}`);
    let addTableColumnSql = tableHelper.addTableColumnSql(tableName, column);
    return this.executeSql(addTableColumnSql);
  }

  insert(tableName: string, values: dataRdb.ValuesBucket | Array<dataRdb.ValuesBucket>): Promise<number> {
    return new Promise<number>((success, error) => {
      LogUtil.info(`insert tableName : ${tableName}, values : ${JSON.stringify(values)}`);
      if (!values) {
        LogUtil.info(`insert failed, values is undefined`);
        error(0);
        return;
      }
      if (values instanceof Array) {
        LogUtil.info(`insert values isArray = ${values.length}`);
        this.rdbStore.beginTransaction();
        this.saveArray(tableName, values).then(data => {
          LogUtil.info(`insert success, data : ${JSON.stringify(data)}`);
          success(data);
          this.rdbStore.commit();
        }).catch((err: Error) => {
          LogUtil.error(`insert failed, err : ${err}`);
          error(err);
          this.rdbStore.commit();
        })
      } else {
        this.rdbStore.insert(tableName, values).then(data => {
          LogUtil.info(`insert success id : ${data}`);
          success(data);
          this.rdbStore.commit();
        }).catch((err: Error) => {
          LogUtil.error(`insert failed, err : ${JSON.stringify(err)}`);
          error(err);
          this.rdbStore.commit();
        })
      }
    })
  }

  private saveArray(tableName: string, values: Array<dataRdb.ValuesBucket>): Promise<number> {
    return new Promise<number>((success, error) => {
      if (!values || values.length === 0) {
        error(0);
        return;
      }
      let index = 0
      let callback = (data: number, err: Error) => {
        if (err) {
          LogUtil.info(`saveArray failed, err : ${err}`);
          error(err);
          return;
        }
        if (data) {
          if (index < values.length - 1) {
            this.saveData(tableName, values, ++index, callback);
          } else {
            success(data);
          }
        }
      }
      this.saveData(tableName, values, index, callback);
    })
  }

  private saveData(tableName: string, values: Array<dataRdb.ValuesBucket>, index: number, callback: Function): void   {
    LogUtil.info(`saveData tableName : ${tableName}, index : ${JSON.stringify(index)}`);
    this.rdbStore.insert(tableName, values[index]).then((data: number) => {
      LogUtil.info(`saveData success id : ${data}`);
      callback(data);
    }).catch((err: Error) => {
      LogUtil.error(`saveData failed, err : ${err}`);
      callback(err);
    })
  }

  update(values: dataRdb.ValuesBucket, rdbPredicates: dataRdb.RdbPredicates): Promise<number> {
    return this.rdbStore.update(values, rdbPredicates);
  }

  query(rdbPredicates: dataRdb.RdbPredicates, columns?: Array<string>): Promise<dataRdb.ResultSet> {
    LogUtil.info(`query rdbPredicates : ${JSON.stringify(rdbPredicates)}`);
    return this.rdbStore.query(rdbPredicates, columns);
  }

  queryAll(tableName: string): Promise<dataRdb.ResultSet> {
    LogUtil.info(`queryAllSize tableName : ${tableName}`);
    return this.rdbStore.querySql(`select * from ${tableName}`);
  }

  queryBySql(sql: string, bindArgs?: Array<dataRdb.ValueType>): Promise<dataRdb.ResultSet> {
    LogUtil.info(`queryBySql sql : ${sql}`);
    return this.rdbStore.querySql(sql, bindArgs);
  }

  delete(rdbPredicates: dataRdb.RdbPredicates): Promise<number> {
    LogUtil.info(`delete rdbPredicates : ${JSON.stringify(rdbPredicates)}`);
    return this.rdbStore.delete(rdbPredicates);
  }
}

操作类TableHelper

定义表操作类TableHelper

import { LogUtil } from '../../utils/LogUtil';
import ColumnInfo from '../model/ColumnInfo';

class TableHelper {
  createTableSql(tableName: string, columns: Array<ColumnInfo>): string {
    let sql = `create table if not exists ${tableName}(`;
    for (let column of columns) {
      sql = sql.concat(`${column.name} ${column.type}`);
      sql = sql.concat(`${column.length && column.length > 0 ? `(${column.length})` : ''}`);
      sql = sql.concat(`${column.primary ? ' primary key' : ''}`);
      sql = sql.concat(`${column.autoincrement ? ' autoincrement' : ''}`);
      sql = sql.concat(`${column.nullable ? '' : ' not null'}`);
      sql = sql.concat(', ');
    }
    sql = `${sql.substring(0, sql.length - 2)})`;
    return sql;
  }

  addTableColumnSql(tableName: string, column: ColumnInfo): string {
    LogUtil.info(`TableHelper updateTableSql : ${JSON.stringify(column)}`);
    let sql = `alter table ${tableName} add `;
    sql = sql.concat(`${column.name} ${column.type}`);
    sql = sql.concat(`${column.length && column.length > 0 ? `(${column.length})` : ''}`);
    LogUtil.info(`TableHelper updateTableSql : ` + sql);
    return sql;
  }

  deleteTableSql(tableName: string): string {
    LogUtil.info(`TableHelper deleteTableSql : ${JSON.stringify(tableName)}`);
    return `drop table if exists ${tableName}`;
  }
}

const tableHelper = new TableHelper();
export default tableHelper;

公共操作类RdbUtils

import { LogUtil } from '../../utils/LogUtil';
import ColumnInfo from '../model/ColumnInfo';
import { RdbHelper } from './RdbHelper';
import { RdbHelperImp } from './RdbHelperImp';
import dataRdb from '@ohos.data.relationalStore';

let dbContext: Context;
let mDatabaseName: string = '';

export class RdbUtils {
  private rdbHelpers = new Map<string, RdbHelper>();

  initDb(context: Context, databaseName: string) {
    dbContext = context;
    mDatabaseName = databaseName;
  }

  createDb(): Promise<RdbHelper> {
    return new Promise<RdbHelper>((success, error) => {
      let dbName = mDatabaseName;
      if (!dbContext || !dbName || dbName.length === 0) {
        error("init err");
        return;
      }
      let dbHelper = this.rdbHelpers.get(dbName);
      if (!dbHelper) {
        LogUtil.info(`initRdb  RdbUtils success`);
        let rdbHelper: RdbHelper = new RdbHelperImp(dbName);
        rdbHelper.getRdb(dbContext).then(data => {
          this.rdbHelpers.set(dbName, data);
          success(data);
        }).catch((err: Error) => {
          error(err);
        })
      } else {
        success(dbHelper);
      }
    })
  }

  deleteDb(context: Context, dbName: string): Promise<void> {
    this.rdbHelpers.delete(dbName);
    return dataRdb.deleteRdbStore(context, dbName);
  }

  createTable(tableName: string, columns: Array<ColumnInfo>): Promise<void> {
    return this.createDb().then(dbHelper => {
      return dbHelper.createTable(tableName, columns);
    });
  }

  isCreateTable(tableName: string, columns: Array<ColumnInfo>): Promise<boolean> {
    return this.createTable(tableName, columns).then(() => {
      return true;
    }).catch((error: Error) => {
      LogUtil.error('RdbUtils', 'create table error ' + JSON.stringify(error));
      return false;
    });
  }

  deleteTable(tableName: string): Promise<void> {
    return this.createDb().then(dbHelper => {
      return dbHelper.deleteTable(tableName);
    })
  }

  executeSql(sql: string): Promise<void> {
    return this.createDb().then(dbHelper => {
      return dbHelper.executeSql(sql);
    })
  }

  addTableColumn(tableName: string, column: ColumnInfo): Promise<void> {
    return this.createDb().then(dbHelper => {
      return dbHelper.addTableColumn(tableName, column);
    })
  }

  insert(tableName: string, values: dataRdb.ValuesBucket | Array<dataRdb.ValuesBucket>): Promise<number> {
    return this.createDb().then(dbHelper => {
      return dbHelper.insert(tableName, values);
    })
  }

  update(values: dataRdb.ValuesBucket, rdbPredicates: dataRdb.RdbPredicates): Promise<number> {
    return this.createDb().then(dbHelper => {
      return dbHelper.update(values, rdbPredicates);
    })
  }

  query(rdbPredicates: dataRdb.RdbPredicates, columns?: Array<string>): Promise<dataRdb.ResultSet> {
    return this.createDb().then(dbHelper => {
      return dbHelper.query(rdbPredicates, columns);
    })
  }

  queryAll(tableName: string): Promise<dataRdb.ResultSet> {
    return this.createDb().then(dbHelper => {
      return dbHelper.queryAll(tableName);
    })
  }

  queryBySql(sql: string, bindArgs?: Array<dataRdb.ValueType>): Promise<dataRdb.ResultSet> {
    return this.createDb().then(dbHelper => {
      return dbHelper.queryBySql(sql, bindArgs);
    })
  }

  del(rdbPredicates: dataRdb.RdbPredicates): Promise<number> {
    return this.createDb().then(dbHelper => {
      return dbHelper.delete(rdbPredicates);
    })
  }
}

let rdbUtils = new RdbUtils();
export default rdbUtils as RdbUtils;

公共操作类使用

  1. 如何使用公共操作类

        // 初始化保存卡片数据库
        RdbUtils.initDb(this.context, Const.RDB_NAME.dbName ? Const.RDB_NAME.dbName : '');
        await RdbUtils.createDb();
        RdbUtils.createTable(Const.FORM_INFO.tableName ? Const.FORM_INFO.tableName : '', columnFormInfoList)
          .catch((err: Error) => {
            LogUtil.error(`RdbHelper formInfo err : ${JSON.stringify(err)}`);
          });
    
  2. 关系型数据库这里使用了接口型开发,使用Map缓存数据库对象,如果Map包含指定数据库名,直接从Map缓存返回,否则创建数据库,并缓存到Map里。

卡片信息API

import RdbUtils from '../database/rdb/RdbUtils';
import FormInfoModel from '../model/FormInfoModel';
import { LogUtil } from '../utils/LogUtil';
import dataRdb from '@ohos.data.relationalStore';
import { RdbConstants as Const } from '../constant/RdbConstants';

class FormInfoApi {

  public insertData(formInfo: FormInfoModel, callback: Function): void {
    const valueBucket = generateBucket(formInfo);
    RdbUtils.insert('formInfo', valueBucket).then(result => {
      callback(result);
    });
    LogUtil.info('FormInfoTable', 'Insert formInfo finished.');
  }

  public queryFormData(callback: Function): void {
    let predicates = new dataRdb.RdbPredicates(Const.FORM_INFO.tableName ? Const.FORM_INFO.tableName : '');
    RdbUtils.query(predicates).then(resultSet => {
      let count = resultSet.rowCount;
      if (count === 0) {
        callback([]);
      } else {
        resultSet.goToFirstRow();
        let resultArray: Array<FormInfoModel> = new Array<FormInfoModel>();
        do {
          let result = new FormInfoModel();
          result.formId = resultSet.getString(resultSet.getColumnIndex('formId'));
          result.formName = resultSet.getString(resultSet.getColumnIndex('formName'));
          result.formDimension = resultSet.getLong(resultSet.getColumnIndex('formDimension'));
          resultArray.push(result);
        } while (resultSet.goToNextRow());
        resultSet.close();
        callback(resultArray);
      }
    }).catch((error: Error) => {
      LogUtil.error('FormInfoTable', 'queryFormData error ' + JSON.stringify(error));
    });
  }

  public deleteFormData(formId: string): void {
    let predicates = new dataRdb.RdbPredicates(Const.FORM_INFO.tableName ? Const.FORM_INFO.tableName : '');
    predicates.equalTo('formId', formId);
    RdbUtils.del(predicates).catch((error: Error) => {
      LogUtil.error('FormInfoTable', 'deleteFormData error ' + JSON.stringify(error));
    });
  }
}

function generateBucket(formInfo: FormInfoModel): dataRdb.ValuesBucket {
  let valueBucket = {} as dataRdb.ValuesBucket;
  Const.FORM_INFO.columns?.forEach((item: string) => {
    if (item !== 'id') {
      switch (item) {
        case 'formId':
          valueBucket[item] = formInfo.formId;
          break;
        case 'formName':
          valueBucket[item] = formInfo.formName;
          break;
        case 'formDimension':
          valueBucket[item] = formInfo.formDimension;
          break;
        default:
          break;
      }
    }
  });
  return valueBucket;
}

let formInfoApi = new FormInfoApi();
export default formInfoApi as FormInfoApi;

卡片保存操作类FormUtils

import FormInfoApi from '../api/FormInfoApi';
import RdbUtils from '../database/rdb/RdbUtils';
import FormInfoModel from '../model/FormInfoModel';
import { RdbConstants as Const } from '../constant/RdbConstants';
import { columnFormInfoList } from '../database/model/RdbColumnModel';
import { LogUtil } from './LogUtil';
import formProvider from '@ohos.app.form.formProvider';
import formBindingData from '@ohos.app.form.formBindingData';
import http from '@ohos.net.http';
import { RequestConstants } from '../constant/RequestConstants';
import { ResponseArray } from '../../model/StandardResponse';
import { BusinessError } from '@ohos.base';

class FormUtils {

  public insertFormData(context: Context, formInfo: FormInfoModel): void {
    LogUtil.info('xx 初始化数据库')
    RdbUtils.initDb(context, Const.RDB_NAME.dbName ? Const.RDB_NAME.dbName : '');
    LogUtil.info('xx 初始化数据表')
    let isCreatePromise = RdbUtils.isCreateTable(Const.FORM_INFO.tableName ?
    Const.FORM_INFO.tableName : '', columnFormInfoList);
    isCreatePromise.then((result: boolean) => {
      if (!result) {
        LogUtil.error(Const.TAG, 'xx insertFormData form table create error');
        return;
      }
      LogUtil.info('xx 插入卡片数据')
      FormInfoApi.insertData(formInfo, (isDone: number) => {
        if (isDone) {
          LogUtil.info(Const.TAG, 'insert formInfo success: ' + JSON.stringify(isDone));
          LogUtil.info('xx 插入卡片数据成功')
          this.queryForms();
        } else {
          LogUtil.info('xx 插入卡片数据失败')
        }
      });
    });
  }

  public deleteFormData(context: Context, formId: string): void {
    RdbUtils.initDb(context, Const.RDB_NAME.dbName ? Const.RDB_NAME.dbName : '');
    let isCreatePromise = RdbUtils.isCreateTable(Const.FORM_INFO.tableName ?
    Const.FORM_INFO.tableName : '', columnFormInfoList);
    isCreatePromise.then((result: boolean) => {
      if (!result) {
        LogUtil.error(Const.TAG, 'deleteFormData form table create error');
        return;
      }
      FormInfoApi.deleteFormData(formId);
    });
  }

  /**
   * Update form operation
   */
  public queryForms(): void {
    LogUtil.info('xx 查询所有卡片信息')
    FormInfoApi.queryFormData((resultSet: Array<FormInfoModel>) => {
      resultSet.forEach((item: FormInfoModel) => {
        this.updateArticleCards(item);
      });
    });
  }

  public updateCards(context: Context): void {
    RdbUtils.initDb(context, Const.RDB_NAME.dbName ? Const.RDB_NAME.dbName : '');
    let isCreatePromise = RdbUtils.isCreateTable(Const.FORM_INFO.tableName ?
    Const.FORM_INFO.tableName : '', columnFormInfoList);
    isCreatePromise.then((result: boolean) => {
      if (!result) {
        LogUtil.error(Const.TAG, 'updateCards form table create error');
        return;
      }
      this.queryForms();
    });
  }

  private updateArticleCards(formInfo: FormInfoModel): void {
    LogUtil.info('xx 更新卡片信息')
    if (formInfo.formDimension === Const.DEFAULT_DIMENSION_4X4) {
      LogUtil.info('xx 更新4x4卡片信息')
      this.getNewsList(formInfo);
    }
  }

  getNewsList(formInfo: FormInfoModel) {
    let httpRequest = http.createHttp()
    const now = new Date();
    const monthStr = String(now.getMonth() + 1).padStart(2, '0');
    const dayStr = String(now.getDate()).padStart(2, '0');

    httpRequest.request(RequestConstants.EVENT_HISTORY_URL, {
      method: http.RequestMethod.POST,
      header: {
        'Content-Type': 'application/json'
      },
      extraData: {
        "token": RequestConstants.TOKEN_KEY,
        "monthday": `${monthStr}${dayStr}`,
        "page": 1
      },
      expectDataType: http.HttpDataType.OBJECT
    }, (err, res) => {
      if (!err) {
        let standardResponse:ResponseArray = res.result as ResponseArray;
        console.info('xx Code:' + standardResponse.code);

        if (standardResponse.code === 200) {
          let newsArticles = standardResponse.data;
          LogUtil.info('xx 数据:' + JSON.stringify(newsArticles))
          LogUtil.info('xx 卡片:' + JSON.stringify(formInfo))

          let obj = formBindingData.createFormBindingData({'newsArticles': newsArticles});
          try {
            formProvider.updateForm(formInfo.formId, obj).then(() => {
              LogUtil.info('xx formProvider updateForm success');
            }).catch((error: BusinessError) => {
              LogUtil.info('xx formProvider updateForm, error:' + JSON.stringify(error));
            });
          } catch (error) {
            LogUtil.info(`xx catch err->${JSON.stringify(error)}`);
          }
        }
        LogUtil.info(`xx get news article data ---> `)


      } else {
        console.info('error:' + JSON.stringify(err));
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁。
        httpRequest.destroy();
      }
    })
  }

}

export default new FormUtils();

http://www.kler.cn/a/429982.html

相关文章:

  • 继续坚持与共勉
  • windows中,git bash 使用conda命令
  • 金融项目实战 01|功能测试分析与设计
  • 美国大学的计算机科学专业排名
  • Jenkins触发器--在其他项目执行后构建
  • maven高级(day15)
  • 商业银行基于容器云的分布式数据库架构设计与创新实践
  • JavaScript 数组的高级用法与最佳实践
  • 如何解决 java.nio.charset.CoderMalfunctionError: 编码器故障错误问题?亲测有效的解决方法!
  • 分布式搜索引擎之elasticsearch基本使用1
  • Java快速分组技术解析
  • 1.1 Beginner Level学习之“编写简单的发布服务器和订阅服务器”(第十二节)
  • 逆波兰算法详解及应用(计算数学表达式)
  • 自动驾驶领域常用的软件与工具
  • 使用Docker安装Qdrant向量数据库
  • 013-SpringBoot 定义优雅的全局异常处理方式
  • ubuntu20.04安装anygrasp_sdk
  • 个人IP建设:简易指南
  • sql常见50道查询练习题
  • 【DataWorks最佳实践】权限及安全-风险识别规则响应案例
  • 手机端常见 BUG 深度剖析:成因、表现与解决之道
  • Android 屏蔽安全模式+去掉系统安全模式(SAFE MODE)
  • Orleans使用KafkaStream
  • SQL,根据数据的时间跨度进行不同粒度的统计
  • JavaScript 单例模式的创建与应用
  • 调度系统:DonpinScheduler 执行 Couchbase SQL 脚本的实际例子