HarmonyOS鸿蒙Next中路由带参数跳转页面的问题

HarmonyOS鸿蒙Next中路由带参数跳转页面的问题

咨询描述

我在第一个页面用路由传递参数

router.pushUrl({
  url: 'pages/CPCL',
  params: this.baseConnect
}).then(() => {
  console.info('Succeeded in jumping to the CPCL page.')
}).catch((err: BusinessError) => {
  console.error(`Failed to jump to the CPCL page. Code is ${err.code}, message is ${err.message}`)
})

第二个页面接收数据

onPageShow(): void {
  const params = router.getParams() as BaseConnection; // 获取传递过来的参数对象
  if (params) {
    this.baseConnect = params
    this.helper = new PrinterCPCLHelper(this.baseConnect)
  }
}

然后我执行这个函数时报错了

if (!this.baseConnect.isConnect()) {
  promptAction.showToast({ message: "请先连接打印机", duration: 2000 })
  this.message = "请先连接打印机"
  return
}

报的错误是

[main_thread.cpp:1589]
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E com.hy.common is about to exit due to RuntimeError
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E Error type: TypeError
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E Error name: TypeError
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E Error message: is not callable
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E SourceCode:
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E if (!this.baseConnect.isConnect()) {
02-27 15:14:06.508 60695-60695 C01317/com.hy.common/AppKit com.hy.common E ^

更多关于HarmonyOS鸿蒙Next中路由带参数跳转页面的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

如果参数没有传过来,就会导致异常crash,目前可以判断的是 this.baseConnect 可能是不存在 导致读取 isConnect() 应用crash了,router传参不能传递方法

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-router#routeroptions

更多关于HarmonyOS鸿蒙Next中路由带参数跳转页面的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


router无法传递map类型的数据,param中只能包含基础类型的数据,router传参请参考:zh-cn/application-dev/reference/apis-arkui/js-apis-router.md · OpenHarmony/docs - 码云 - 开源中国,推荐使用Navigation进行复杂数据类型的传参。

参考链接:[https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkui-261-V5]

在HarmonyOS鸿蒙Next中,路由带参数跳转页面可以通过router.push方法实现。参数可以附加在url中,例如:router.push({ url: 'pages/PageName', params: { key: 'value' } })。目标页面通过router.getParams获取传递的参数。确保目标页面在pages目录下,并在config.json中正确配置路由。

从错误信息来看,问题出在调用this.baseConnect.isConnect()方法时,报错提示"is not callable"。这通常说明baseConnect对象中的isConnect不是一个可调用的方法。

可能原因及解决方案:

  1. 参数序列化问题: 路由传递的对象会被序列化,可能导致方法丢失。建议只传递纯数据对象,不要传递带有方法的对象。

  2. 类型转换问题: router.getParams()返回的是序列化后的对象,直接强制类型转换为BaseConnection可能不完整。

建议修改为:

// 发送方改为传递纯数据
router.pushUrl({
  url: 'pages/CPCL',
  params: JSON.parse(JSON.stringify(this.baseConnect)) 
});

// 接收方重建对象
onPageShow(): void {
  const params = router.getParams();
  if (params) {
    this.baseConnect = new BaseConnection(params); // 使用构造函数重建对象
    this.helper = new PrinterCPCLHelper(this.baseConnect);
  }
}
  1. 检查BaseConnection类: 确保isConnect是类的实例方法而非静态方法,且已正确定义。
回到顶部