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.1.18 框架之网关协议-Variables变量

    我们在应用开发过程有一种特殊情况在后端逻辑编写的时候需要知道请求的发起入口,平台利用GQL协议中的Variables属性来传递信息,本文就介绍如何获取。 一、前端附带额外变量 属性名 类型 说明 scene String 菜单入口 表4-1-18-1 前端附带额外变量 图4-1-18-1 variables信息中的scene 二、后端如何接收variables信息 通过PamirsSession.getRequestVariables()可以得到PamirsRequestVariables对象。 三、第一个variable(举例) Step1 修改PetTalentAction,获取得到前端传递的Variables package pro.shushi.pamirs.demo.core.action; ……类引用 @Model.model(PetTalent.MODEL_MODEL) @Component public class PetTalentAction { ……其他代码 @Function.Advanced(type= FunctionTypeEnum.QUERY) @Function.fun(FunctionConstants.queryPage) @Function(openLevel = {FunctionOpenEnum.API}) public Pagination<PetTalent> queryPage(Pagination<PetTalent> page, IWrapper<PetTalent> queryWrapper){ String scene = (String)PamirsSession.getRequestVariables().getVariables().get("scene"); System.out.println("scene: "+ scene); ……其他代码 } ……其他代码 } 图4-1-18-2 修改PetTalentAction Step2 重启验证 点击宠物达人不同菜单入口,查看效果 图4-1-18-3 示例效果(一) 图4-1-18-4 示例效果(二)

    2024年5月23日
    84700
  • 书籍封面

    2024年5月23日
    3.0K00
  • 4.1.17 框架之网关协议-GraphQL协议

    GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。 一个 GraphQL 服务是通过定义类型和类型上的字段来创建的,然后给每个类型上的每个字段提供解析函数。例如,一个 GraphQL 服务告诉我们当前登录用户是 me,这个用户的名称可能像这样: type Query { me: User } type User { id: ID name: String } 图4-1-17-1 GraphQL定义类型和字段示意 一并的还有每个类型上字段的解析函数: function Query_me(request) { return request.auth.user; } function User_name(user) { return user.getName(); } 图4-1-17-2 每个类型上字段的解析函数示意 一旦一个 GraphQL 服务运行起来(通常在 web 服务的一个 URL 上),它就能接收 GraphQL 查询,并验证和执行。接收到的查询首先会被检查确保它只引用了已定义的类型和字段,然后运行指定的解析函数来生成结果。 例如这个查询: { me { name } } 图4-1-17-3 GraphQL查询请求示意 会产生这样的JSON结果: { "me": { "name": "Luke Skywalker" } } 图4-1-17-4 GraphQL查询结果示意 了解更多 https://graphql.cn/learn/

  • 4.2.7 框架之翻译工具

    一、说明 Oinone目前的默认文案是中文,如果需要使用其他语言,Oinone也提供一系列的翻译能力。 二、定义语言文件 在src/local下新增一个名为zh_cn.ts文件: 图4-2-7-1 语言文件 编辑zh_cn.ts文件,增加以下内容: const zhCN = { demo: { test: '这是测试' } } export default zhCN 图4-2-7-2 语言内容格式示意 在mian.ts注册语言资源: import { LanguageType, registryLanguage} from '@kunlun/dependencies'; import Zh_cn from './local/zh_cn' registryLanguage(LanguageType['zh-CN'], Zh_cn); 图4-2-7-3 注册语言 三、Vue模板使用 <template> <div class="petFormWrapper"> <form :model="formState" @finish="onFinish"> <a-form-item :label="translate('demo.test')" 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({ // 引入translate props: ['onChange', 'reloadData', 'serviceErrors', 'translate'], 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);…

    2024年5月23日
    79400
  • 3.6 问题排查工具

    当前端发起对应用的访问时,如果出现错误,那么我们可以通过以下方式进行简易排查,如果排查不出来,则也可以把排查工具给出的信息发送给Oinone官方售后进行进一步分析。本文将通过模拟异常信息,来介绍排查工具,提供了哪些辅助信息帮我们来快速定位问题。 排查工具基础介绍 通过前端页面的 /debug 路由路径访问调试工具的页面,假设我们的前端页面访问地址为http://localhost:6800,那么我们的排查工具请求路径就是 http://localhost:6800/debug排查工具可以帮我们排查前端页面元数据异常和后端接口的异常 排查前端页面元数据 将问题页面浏览器地址栏内 page 后的部分复制到调试工具的 debug 路由后重新发起请求,如图可以看到调试工具展示的信息,可以根据这些信息排查问题。 排查后端接口 后端接口出现问题后,打开(在原页面)浏览器的调试工具,切换到“网络”的标签页,在左侧的历史请求列表中找到需要调试的请求,右键会弹出菜单,点击菜单中的 “复制”,再次展开该菜单,点击二级菜单中的“以 fetch 格式复制”,这样可以复制到调试所需要的信息 2.复制调试信息到“接口调试”标签页内的文本框内,点击“发起请求”按钮获取调试结果 我们可以看到页面展示了该接口的各种调试信息,我们可以据此排查问题。 场景化的排查思路 业务代码中存在代码bug 报错后发起调试请求,我们可以看到,调试工具直接给出了异常抛出的具体代码所在位置,此时再切换到“全部堆栈”下,可以看到是业务类的233行导致的空指针异常,查看代码后分析可得是data.getName().eqauls方法在调用前未做条件判断补全该判断后代码可以正常执行 业务代码中没有直接的错误,异常在平台代码中抛出 报错后发起调试请求可以看到异常不在业务代码内再切换到“全部堆栈”,可以看到具体异常信息,提示core_demo_item表出现了重复的主键,该表是DemoItem模型的我们还可以切换到“sql调试”的标签页,可以看到出错的具体sql语句经过分析可以得知是240行的data.create()�重复创建数据导致的。 三、排查工具无法定位怎么办 当我们通过排查工具还是没有定位到问题的时候,可以通过调试页面的“下载全部调试数据”和“下载调试数据”按钮将调试信息的数据发送给官方售后人员帮助我们定位排查问题。 点击页面最顶部的“下载全部调试数据”按钮,可以下载页面调试数据和接口调试数据点击“调试接口”标签页内的“下载调试数据”按钮,可以下载接口调试数据 四、排查工具细节

    2024年5月23日
    1.2K00

Leave a Reply

登录后才能评论