4.2.2 框架之MessageHub

一、MessageHub

请求出现异常时,提供”点对点“的通讯能力

二、何时使用

错误提示是用户体验中特别重要的组成部分,大部分的错误体现在整页级别,字段级别,按钮级别。友好的错误提示应该是怎么样的呢?我们假设他是这样的

  • 与用户操作精密契合
    • 当字段输入异常时,错误展示在错误框底部
    • 按钮触发服务时异常,错误展示在按钮底部
  • 区分不同的类型
    • 错误
    • 成功
    • 警告
    • 提示
    • 调试
  • 简洁易懂的错误信息

在oinone平台中,我们怎么做到友好的错误提示呢?接下来介绍我们的MessageHub,它为自定义错误提示提供无限的可能。

三、如何使用

订阅

import { useMessageHub, ILevel } from "@kunlun/dependencies"
const messageHub = useMessageHub('当前视图的唯一标识');
/* 订阅错误信息 */
messageHub.subscribe((errorResult) => {
 console.log(errorResult)
})
/* 订阅成功信息 */
messageHub.subscribe((errorResult) => {
 console.log(errorResult)
}, ILevel.SUCCESS)

图4-2-2-1 订阅的示例代码

销毁

/** 
* 在适当的时机销毁它
* 如果页面逻辑运行时都不需要销毁,在页面destroyed是一定要销毁,重要!!!
*/
messageHub.unsubscribe()

图4-2-2-2 销毁的示例代码

四、实战

让我们把3.5.7.5【自定义视图-表单】一文中的自定义表单进行改造,加入我们的messageHub,模拟在表单提交时,后端报错信息在字段下方给予提示。

Step1 (后端)重写PetType的创建函数

重写PetType的创建函数,在创建逻辑中通过MessageHub返回错误信息,返回错误信息的同时要设置paths信息方便前端处理

@Action.Advanced(name = FunctionConstants.create, managed = true)
    @Action(displayName = "确定", summary = "创建", bindingType = ViewTypeEnum.FORM)
    @Function(name = FunctionConstants.create)
    @Function.fun(FunctionConstants.create)
    public PetType create(PetType data){
        List<Object> paths = new ArrayList<>();
        paths.add("demo.PetType");
        paths.add("kind");
        PamirsSession.getMessageHub().msg(new Message().msg("kind error").setPath(paths).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR));

        List<Object> paths2 = new ArrayList<>();
        paths2.add("demo.PetType");
        paths2.add("name");
        PamirsSession.getMessageHub().msg(new Message().msg("name error").setPath(paths2).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR));
//        data.create();
        return data;
    }

图4-2-2-3 (后端)重写PetType的创建函数

Step 2 修改PetForm.vue

<template>
  <div class="petFormWrapper">
    <form :model="formState" @finish="onFinish">
      <a-form-item label="品种种类" id="name" name="kind" :rules="[{ required: true, message: '请输入品种种类!', trigger: 'focus' }]">
        <a-input v-model:value="formState.kind" @input="(e) => onNameChange(e, 'kind')" />
        <span style="color: red">{{ getServiceError('kind') }}</span>
      </a-form-item>

      <a-form-item label="品种名" id="name" name="name" :rules="[{ required: true, message: '请输入品种名!', trigger: 'focus' }]">
        <a-input v-model:value="formState.name" @input="(e) => onNameChange(e, 'name')" />
        <span style="color: red">{{ getServiceError('name') }}</span>
      </a-form-item>
    </form>
  </div>
</template>-

<script lang="ts">
import { defineComponent, reactive } from 'vue';
import { Form } from 'ant-design-vue';

export default defineComponent({
  props: ['onChange', 'reloadData', 'serviceErrors'],
  components: { Form },
  setup(props) {
    const formState = reactive({
      kind: '',
      name: '',
    });

    const onFinish = () => {
      console.log(formState);
    };

    const onNameChange = (event, name) => {
      props.onChange(name, event.target.value);
    };

    const reloadData = async () => {
      await props.reloadData();
    };
    // 提示服务器异常消息
    const getServiceError = (name: string) => {
      const error = props.serviceErrors.find(error => error.name === name);
      return error ? error.error : '';
    }

    return {
      formState,
      reloadData,
      onNameChange,
      onFinish,
      getServiceError
    };
  }
});
</script>

图4-2-2-4 修改PetForm.vue

Step3 PetFormViewWidget.ts

import { constructOne, FormWidget, queryOne, SPI, ViewWidget, Widget, IModel, getModelByUrl, getModel, getIdByUrl, FormWidgetV3, CustomWidget, MessageHub, useMessageHub, ILevel, CallChaining } from '@kunlun/dependencies';
import PetFormView from './PetForm.vue';

@SPI.ClassFactory(CustomWidget.Token({ widget: 'PetForm' }))
export class PetFormViewWidget extends FormWidgetV3 {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(PetFormView);
    return this;
  }

  /**
   * 数据提交
   * @protected
   */
  @Widget.Reactive()
  @Widget.Inject()
  protected callChaining: CallChaining | undefined;

  private modelInstance!: IModel;

  // MessageHub相关逻辑
  private messageHub!: MessageHub;

  @Widget.Reactive()
  private serviceErrors: Record<string, unknown>[] = [];

  /**
   * 重要!!!!
   * 当字段改变时修改formData
   * */
  @Widget.Method()
  public onFieldChange(fieldName: string, value) {
    this.setDataByKey(fieldName, value);
  }

  /**
   * 表单编辑时查询数据
   * */
  public async fetchData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance?.modelFields;
    try {
      const id = getIdByUrl();
      const data = (await queryOne(this.modelInstance.model, (content[0] || { id }) as Record<string, string>, fields, variables, context)) as Record<string, unknown>;

      this.loadData(data);
      this.setBusy(false);
      return data;
    } catch (e) {
      console.error(e);
    } finally {
      this.setBusy(false);
    }
  }

  /**
   * 新增数据时获取表单默认值
   * */
  @Widget.Method()
  public async constructData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance.modelFields;
    const reqData = content[0] || {};
    const data = await constructOne(this.modelInstance!.model, reqData, fields, variables, context);
    return data as Record<string, unknown>;
  }

  @Widget.Method()
  private async reloadData() {
    const data = await this.constructData();
    // 覆盖formData
    this.setData(data);
  }

  @Widget.Method()
  public onChange(name, value) {
    this.formData[name] = value;
  }

  protected async mounted() {
    super.mounted();
    const modelModel = getModelByUrl();
    this.modelInstance = await getModel(modelModel);
    this.fetchData();
    this.messageHub = useMessageHub('messageHubCode');
    this.messageHub.subscribe((result) => {
      this.serviceErrors = [];
      // 收集错误信息
      if (Array.isArray(result)) {
        const errors = result.map((res) => {
          const path = res.path[1],
            error = res.message;
          return {
            name: path,
            error
          };
        });
        this.serviceErrors = errors;
      }
    });
    this.messageHub.subscribe((result) => {
      console.log(result);
    }, ILevel.SUCCESS);
    // 数据提交钩子函数!!!
    this.callChaining?.callBefore(() => {
      return this.formData;
    });
  }
}

图4-2-2-5 PetFormViewWidget.ts

Step4 刷新页面看效果

image.png

图4-2-2-6 刷新页面看效果

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9303.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:35
下一篇 2024年5月23日

相关推荐

  • 4.2.6 框架之网络请求-拦截器

    在整个http的链路中,异常错误对前端来说尤为重要,他作用在很多不同的场景,通用的比如500, 502等; 一个好的软件通常需要在不同的错误场景中做不同的事情。当用户cookie失效时,希望能自动跳转到登录页;当用户权限发生变更时,希望能跳转到一个友好的提示页;那么如何满足这些个性化的诉求呢?接下来让我们一起了解oinone前端网络请求-拦截器。 一、入口 在src目录下main.ts中可以看到VueOioProvider,这是系统功能提供者的注册入口 图4-2-6-1 VueOioProvider import interceptor from './middleware/network-interceptor'; VueOioProvider( { http: { callback: interceptor } }, [] ); 图4-2-6-2 拦截器的申明入口 二、middleware 在项目初始化时使用CLI构建初始化前端工程,在src/middleware有拦截器的默认实现: 图4-2-6-3 在src/middleware有拦截器的默认实现 三、interceptor interceptor在请求返回后触发,interceptor有两个回调函数,error和next error参数 graphQLErrors 处理业务异常 networkError 处理网络异常 next extensions 后端返回扩展参数 const interceptor: RequestHandler = (operation, forward) => { return forward(operation).subscribe({ error: ({ graphQLErrors, networkError }) => { console.log(graphQLErrors, networkError); // 默认实现 => interceptor error }, next: ({ extensions }) => { console.log(extensions); // 默认实现 => interceptor next }, }); }; 图4-2-6-4 后端返回扩展参数 四、interceptor error // 定义错误提示等级 const DEFAULT_MESSAGE_LEVEL = ILevel.ERROR; // 错误提示等级 对应提示的报错 const MESSAGE_LEVEL_MAP = { [ILevel.ERROR]: [ILevel.ERROR], [ILevel.WARN]: [ILevel.ERROR, ILevel.WARN], [ILevel.INFO]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO], [ILevel.SUCCESS]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS], [ILevel.DEBUG]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS, ILevel.DEBUG] }; // 错误提示通用函数 const notificationMsg = (type: string = 'error', tip: string = '错误', desc: string = '') => { notification[type]({ message: tip, description: desc }); }; // 根据错误等级 返回错误提示和类型 const getMsgInfoByLevel = (level: ILevel) => { let notificationType = 'info'; let notificationText = translate('kunlun.common.info'); switch (level) { case ILevel.DEBUG: notificationType = 'info'; notificationText = translate('kunlun.common.debug'); break; case ILevel.INFO: notificationType = 'info'; notificationText = translate('kunlun.common.info'); break;…

    2024年5月23日
    88300
  • 6.3 数据审计(改)

    在业务应用中我们经常需要为一些核心数据的变更做审计追踪,记录字段的前后变化、操作IP、操作人、操作地址等等。数据审计模块为此提供了支撑和统一管理。它在成熟的企业的核心业务系统中,需求是比较旺盛的。接下来我们开始学习下数据审计模块 准备工作 pamirs-demo-core的pom文件中引入pamirs-data-audit-api包依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-data-audit-api</artifactId> </dependency> pamirs-demo-boot的pom文件中引入pamirs-data-audit-core和pamirs-third-party-map-core包依赖,数据审计会记录操作人的地址信息,所以也依赖了pamirs-third-party-map-core <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-data-audit-core</artifactId> </dependency> <dependency> <groupId>pro.shushi.pamirs.core.map</groupId> <artifactId>pamirs-third-party-map-core</artifactId> </dependency> pamirs-demo-boot的application-dev.yml文件中增加配置pamirs.boot.modules增加data_audit 和third_party_map,即在启动模块中增加data_audit和third_party_map模块 pamirs: boot: modules: – data_audit – tp_map 为third_party_map模块增加高德接口api,下面e439dda234467b07709f28b57f0a9bd5换成自己的key pamirs: eip: map: gd: key: e439dda234467b07709f28b57f0a9bd5 数据审计 注解式(举例) Step1 新增PetTalentDataAudit数据审计定义类 package pro.shushi.pamirs.demo.core.init.audit; import pro.shushi.pamirs.data.audit.api.annotation.DataAudit; import pro.shushi.pamirs.demo.api.model.PetTalent; @DataAudit( model = PetTalent.MODEL_MODEL,//需要审计的模型 modelName = "宠物达人" ,//模型名称,默认模型对应的displayName //操作名称 optTypes = {PetTalentDataAudit.PETTALENT_CREATE,PetTalentDataAudit.PETTALENT_UDPATE}, fields={"nick","picList.id","picList.url","petShops.id","petShops.shopName"}//需要审计的字段,关系字段用"."连结 ) public class PetTalentDataAudit { public static final String PETTALENT_CREATE ="宠物达人创建"; public static final String PETTALENT_UDPATE ="宠物达人修改"; Step2 修改PetTalentAction的update方法 做审计日志埋点:手工调用 OperationLogBuilder.newInstance().record()方法。需要注意的是这里需要把原有记录的数据值先查出来做对比 @Function.Advanced(type= FunctionTypeEnum.UPDATE) @Function.fun(FunctionConstants.update) @Function(openLevel = {FunctionOpenEnum.API}) public PetTalent update(PetTalent data){ //记录日志 OperationLogBuilder.newInstance(PetTalent.MODEL_MODEL, PetTalentDataAudit.PETTALENT_UDPATE).record(data.queryById().fieldQuery(PetTalent::getPicList).fieldQuery(PetTalent::getPetShops),data); PetTalent existPetTalent = new PetTalent().queryById(data.getId()); if(existPetTalent !=null){ existPetTalent.fieldQuery(PetTalent::getPicList); existPetTalent.fieldQuery(PetTalent::getPetShops); existPetTalent.relationDelete(PetTalent::getPicList); existPetTalent.relationDelete(PetTalent::getPetShops); } data.updateById(); data.fieldSave(PetTalent::getPicList); data.fieldSave(PetTalent::getPetShops); return data; } Step3 重启看效果 修改宠物达人记录对应的字段,然后进入审计模块查看日志

    2024年5月23日
    76500
  • 文件

    文件应用下包含“导入/导出模版、导入任务、导出任务”三个菜单。其中导入/导出任务菜单比较常用。 导入/导出模版 当前版本会为租户的表格视图自动创建导出模版,此处可进行编辑、查看详情的操作。 导入任务 导入任务可以下载导入文档,点击详情可以查看该条记录的导入结果,任务信息分组中可以查看错误信息。 导出任务 和导入任务一致,导出任务菜单中可以下载导出文档,点击详情可以查看该条记录的导出结果,任务信息分组中可以查看错误信息。

    2024年6月20日
    88700
  • 陈浩

    自2017年中国推进数字建设以来,数字经济规模持续增长,“十四五”规划和2035远景目标纲要中明确强调企业和政府需大力推动数字化转型,中国正在迈进一个崭新的数字经济时代。 在这个过程中,软件已经从工具变成信息化的基础设施,如何有效应对该变化所带来的一系列新的核心技术挑战,是整个软件行业发展遇到的另一难题。我认为,开源创新是解决这些难题的有效手段之一,也是未来软件发展的重要方向。如果说,数字化转型是时代趋势,那么开源创新也已成为时代主流。十四五规划纲要首提开源,2021年11月工信部印发《十四五软件和信息技术服务业发展规划》中提到开源重塑软件发展新生态,并将开源重塑软件发展新生态作为十四五期间我国软件产业的四大发展形势之一进行重点阐述。支持国产化开源创新体系发展,建设自己的开源社区和开源平台,其所具有的大众协同、开放共享、持续创新等特点,可有效推动各行业自主可控的数字化转型。 Oinone所倡导的开源理念和生态共建,与国家开源战略不谋而合:将开源作为一种合作手段,通过完善社区注重开源治理,吸引更多的企业和个体参与其中。湖南大学作为首批国家示范性软件学院的双一流建设高校,一直致力于推进和引导国产化开源软件体系的建设,并为此开展多种形式的产学研研究和实践。基于Oinone微服务分布式的设计理念和面向生态的开源特性,湖南大学结合自身在大数据分布式存储、多元异构数据汇聚融合和大数据智能分析等方面的研究成果,与Oinone展开了深度的技术创新合作,并在多个大中型企业数字化应用和数字政府应用中取得了良好的效果。 随着Oinone的开源,相信能激发更多的开发者参与到国产软件建设中,通过开源模式实现更广泛参与方的共享、共创、共生、共赢,构建价值驱动的数字创新生态平台,为我国数字经济发展贡献科技力量。 湖南大学教授:陈浩

    Oinone 7天入门到精通 2024年5月23日
    1.2K00
  • 4.2.1 组件之生命周期

    组件生命周期的意义所在:比如动态创建了「视图、字段」,等它们初始化完成或者发生了修改后要执行业务逻辑,这个时候只能去自定义当前字段或者视图,体验极差,平台应该提供一些列的生命周期,允许其他人调用生命周期的api去执行对应的逻辑。 一、实现原理 图4-2-1-1 实现原理 当用户通过内部API去监听某个生命周期的时候,内部会动态的去创建该生命周期,每个生命周期都有「唯一标识」,内部会根据「唯一标识」去创建对应的「Effect」,Effect会根据生命周期的「唯一标识」实例化一个「lifeCycle」,「lifeCycle」创建完成后,会被存放到「Heart」中,「Heart」是整个生命周期的心脏,当心脏每次跳动的时候(生命周期被监听触发)都会触发对应的生命周期 二、生命周期API API 描述 返回值 View LifeCycle onViewBeforeCreated 视图创建前 ViewWidget onViewCreated 视图创建后 ViewWidget onViewBeforeMount 视图挂载前 ViewWidget onViewMounted 视图挂载后 ViewWidget onViewBeforeUpdate 视图数据发生修改前 ViewWidget onViewUpdated 视图数据修改后 ViewWidget onViewBeforeUnmount 视图销毁前 ViewWidget onViewUnmounted 视图销毁 ViewWidget onViewSubmit 提交数据 ViewWidget onViewSubmitStart 数据开始提交 ViewWidget onViewSubmitSuccess 数据提交成功 ViewWidget onViewSubmitFailed 数据提交失败 ViewWidget onViewSubmitEnd 数据提交结束 ViewWidget onViewValidateStart 视图字段校验 ViewWidget onViewValidateSuccess 校验成功 ViewWidget onViewValidateFailed 校验失败 ViewWidget onViewValidateEnd 校验结束 ViewWidget Field LifeCycle onFieldBeforeCreated 字段创建前 FieldWidget onFieldCreated 字段创建后 FieldWidget onFieldBeforeMount 字段挂载前 FieldWidget onFieldMounted 字段挂载后 FieldWidget onFieldBeforeUpdate 字段数据发生修改前 FieldWidget onFieldUpdated 字段数据修改后 FieldWidget onFieldBeforeUnmount 字段销毁前 FieldWidget onFieldUnmounted 字段销毁 FieldWidget onFieldFocus 字段聚焦 FieldWidget onFieldChange 字段的值发生了变化 FieldWidget onFieldBlur 字段失焦 FieldWidget onFieldValidateStart 字段开始校验 FieldWidget onFieldValidateSuccess 校验成功 FieldWidget onFieldValidateFailed 校验失败 FieldWidget onFieldValidateEnd 校验结束 FieldWidget 表4-2-1-1 生命周期API 上面列出的分别是「视图、字段」的生命周期,目前Action的生命周期还没有,后续再补充。 三、第一个View组件生命周期的监听(举例) Step1 新建registryLifeCycle.ts 新建registryLifeCycle.ts,监听宠物达人的列表页。’宠物达人table_demo_core’为视图名,您需要找后端配合 import { onViewCreated } from '@kunlun/dependencies' function registryLifeCycle(){ onViewCreated('宠物达人table_demo_core', (viewWidget) => { console.log('宠物达人table_demo_core'); console.log(viewWidget); }); } export {registryLifeCycle} 图4-2-1-2 新建registryLifeCycle.ts Step2 修改main.ts 全局注册lifeCycle import { registryLifeCycle } from './registryLifeCycle'; registryLifeCycle(); 图4-2-1-3 修改main.ts Step3 看效果 图4-2-1-4 示例效果 四、第一个Filed组件生命周期的监听(举例) Step1 修改registryLifeCycle.ts 通过onFieldValueChange增加宠物达人搜索视图的name(达人)字段的值变化进行监听。 宠物达人search:name 代表 视图名:字段名 import { onViewCreated , onFieldValueChange} from '@kunlun/dependencies' function registryLifeCycle(){ onViewCreated('宠物达人table_demo_core', (viewWidget) => { console.log('宠物达人table_demo_core'); console.log(viewWidget); }); onFieldValueChange('宠物达人search:name', (filedWidget) => { console.log('宠物达人search:name');…

Leave a Reply

登录后才能评论