HarmonyOS NavPathStack的拦截,能不能在跳转前拦截?

navPathStack.setInterception({
  willShow: (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar",
    operation: NavigationOperation, animated: boolean) => {

    let target: NavDestinationContext = to as NavDestinationContext;

    LogUtils.info("跳到="+target.pathInfo.name)

    BaseUtils.isLogin().then((login:boolean)=>{
      if (!login) {
        if (target.pathInfo.name == RouterPath.FaultReportingPage) {
          LogUtils.info("有的页面需要登录,没登录就先关闭,再去登录")
          target.pathStack.pop();
          target.pathStack.pushPathByName(RouterPath.login, null);
        }
      }
    })
  }
})
}

这个感觉不像是拦截,因为它是先执行了目标界面的aboutToAppear,有没有那种跳转之前就拦截的。

阅读 515
1 个回答

1、依据代码描述场景,参考demo:

// ./CommonRouter/CommonRouter.ets
export class CommonRouter {
  static stack: NavPathStack;
  static instance: CommonRouter;

  static init(stack: NavPathStack) {
    CommonRouter.stack = stack;
  }

  static getInstance() {
    if (!CommonRouter.instance) {
      CommonRouter.instance = new CommonRouter();
    }
    return CommonRouter.instance;
  }

  pushPathByName(routeName: string) {
    CommonRouter.stack.pushPathByName(routeName, '')
  }

  pop() {
    CommonRouter.stack.pop()
  }

  clear() {
    CommonRouter.stack.clear()
  }
}
// ./CommonRouter/CommonRouter.ets

import { CommonRouter} from "./CommonRouter/CommonRouter"
import { PageOne } from './PageOne'
import { PageTwo } from './PageTwo'

@Entry
@Component
struct NavigationExample {
  @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack()

  aboutToAppear() {
    CommonRouter.init(this.pageInfos);
  }

  @Builder
  PageMap(name: string) {
    if (name === 'pageOne') {
      PageOne()
    } else if (name === 'pageTwo') {
      PageTwo()
    } else {
      PageOne()
    }
  }

  build() {
    Navigation(this.pageInfos) {
      Column() {
        Button('pushPageOne', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            CommonRouter.getInstance().pushPathByName('pageOne')
          })
        Button('pushPageTwo', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            CommonRouter.getInstance().pushPathByName('pageTwo')
          })
      }
    }.title('NavIndex')
    .navDestination(this.PageMap)
  }
}

1、上面代码,处理时机,在这俩个函数中可拦截,跳转前拦截,返回拦截。这里可作为您业务逻辑的统一拦截管理,在aboutToAppear 执行前。

2、aboutToAppear 生命周期参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-page-custom-components-lifecycle-V5

pushPathByName(routeName: string) {
  // 跳转页面逻辑拦截 TODO
  console.info('跳转页面逻辑拦截 TODO')
  CommonRouter.stack.pushPathByName(routeName, '')
}

pop() {
  // 返回逻辑拦截 TODO
  console.info('返回逻辑拦截 TODO')
  CommonRouter.stack.pop()
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进