ArkUI-X ; replaceUrl 与 replaceNamedRoute

171 阅读1分钟

探索 ArkUI-X:跨平台开发的请求拦截器封装

最近了解到 ArkUI-X 支持跨平台开发,能够实现“一次开发,多端部署”。于是,我决定尝试封装一个请求拦截器。

需求场景

在接口请求中,如果返回的状态码 code === 401,表示用户的 token 已失效,需要跳转到登录页面重新登录。

初始实现

按照常规逻辑,我写了以下代码:

正常逻辑,接口返回code===401 则跳转回登录页面

//状态码code=401表示token失效,状态码可根据实际接口文档修改
if (res.code === 401) { //跳转登录页
  router.clear() //清空历史页面
  //跳转到登录页
  router.replaceUrl({url:'page/login/index'})
}

这样写编译时,报错:

image.png

问题排查

翻阅官方文档 ArkUI-X 路由 API,发现并没有 router.replaceUrl 这个 API,但找到了一个类似的 router.replaceNamedRoute

于是,我尝试使用 replaceNamedRoute

router.replaceNamedRoute({name:'pages/login/index'},(err)=>{
  console.log(JSON.stringify(err))
})

点击后没有任何反应,查看日志发现输出了错误信息:

翻阅文档得出结论:100004:if the named route is not exist.指定的路由不存在;

该如何配置这个路由 ?官方文档也没给出示例。直到查阅到论坛内的一篇文章: developer.huawei.com/consumer/cn…

直接上手:

  1. 先在 login.ets文件中声明routeName:'loginIndex',并导出这个页面export
@Entry({routeName:'loginIndex'})
@Component
export struct loginCom {
  //...
}
  1. 封装request请求文件中引入,并使用;
//引入登录页路由
import ('../pages/login/login')
...
//代码逻辑
//状态码code=401表示token失效,
if (res.code === 401) { //跳转登录页
  router.clear() //清空历史页面
  //跳转到登录页
  router.replaceNamedRoute({name:'loginIndex'})//此处的name需要与引入页面的routeName 相同
}