在HarmonyOS NEXT开发中pushDestinationByName下个界面返回时候怎么回传值?

在HarmonyOS NEXT开发中pushDestinationByName下个界面返回时候怎么回传值?

阅读 1.2k
avatarAI BotBETA

在HarmonyOS NEXT开发中,通过pushDestinationByName跳转界面后回传值,可通过以下两种方式实现:


方法一:使用 AbilityResult 回调

// 源页面发送跳转请求
import { AbilityResult } from '@ohos.app.ability.UIAbility';

let want = {
  bundleName: "com.example.target",
  abilityName: "TargetAbility",
  parameters: { key: "value" } // 可选:传递参数到目标页面
};

// 通过 startAbilityForResult 发起带返回值的跳转
this.context.startAbilityForResult(want).then((result: AbilityResult) => {
  if (result.resultCode === 0) {
    let returnedData = result.want?.parameters?.returnKey; // 获取回传值
    console.log("Received data: " + returnedData);
  }
});

// 目标页面返回时设置返回值
let resultWant = {
  parameters: { returnKey: "回传的数据" }
};
this.context.terminateSelfWithResult({ resultCode: 0, want: resultWant });

方法二:使用 EventHub 事件总线

// 源页面订阅事件
import { eventHub } from '@ohos.app.ability.UIAbility';

eventHub.on("returnEvent", (data) => {
  console.log("Received data: " + data);
});

// 跳转页面
let want = {
  bundleName: "com.example.target",
  abilityName: "TargetAbility"
};
this.context.startAbility(want);

// 目标页面返回前触发事件
eventHub.emit("returnEvent", "回传的数据");
this.context.terminateSelf();

关键区别:

  1. AbilityResult:适合一次性返回值场景(如弹窗选择)。
  2. EventHub:适合跨页面/跨层级通信,需注意生命周期管理。

注意事项:

  • 如果使用 pushDestinationByName(基于动态路由),建议优先采用 AbilityResult 方式。
  • 确保目标页面调用 terminateSelfWithResult 主动回传值。
1 个回答

解决方法:

class PageParam { 
  constructor(num_: number) { 
    this.num = num_; 
  } 
 
  num: number = 0; 
} 
 
class BackParam { 
  constructor(backStr_: string) { 
    this.backStr = backStr_; 
  } 
 
  backStr: string = ""; 
} 
 
@Component 
struct PageOne { 
  private stack: NavPathStack | null = null; 
  private name: string = ""; 
  private paramNum: number = 0; 
  @State backStr: string = "暂无信息" 
 
  build() { 
    NavDestination() { 
      Column() { 
        Text("NavPathInfo: name: " + this.name + ", paramNum: " + this.paramNum) 
        Text(this.backStr) 
 
        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule }) 
          .width('80%') 
          .height(40) 
          .margin(20) 
          .onClick(() => { 
            if (this.stack) { 
              let p = new PageParam(this.paramNum + 1); 
              this.stack.pushPath({ 
                name: "pageOne", param: p, onPop: (popInfo: PopInfo) => { 
                  console.info(' result: ' + JSON.stringify(popInfo.result)); 
                  this.backStr = popInfo.result['backStr'] as string 
                } 
              }); 
            } 
          }) 
        Button('pop', { stateEffect: true, type: ButtonType.Capsule }) 
          .width('80%') 
          .height(40) 
          .margin(20) 
          .onClick(() => { 
            this.stack?.pop(new BackParam("返回信息" + this.paramNum)) 
          }) 
      } 
      .width('100%') 
      .height('100%') 
    } 
    .hideTitleBar(true) 
    .title('pageOne') 
    .onReady((ctx: NavDestinationContext) => { 
      // 在NavDestination中能够拿到传来的NavPathInfo和当前所处的NavPathStack 
      try { 
        this.name = ctx?.pathInfo?.name; 
        this.paramNum = (ctx?.pathInfo?.param as PageParam)?.num; 
        this.stack = ctx.pathStack; 
      } catch (e) { 
        console.log(`testTag onReady catch exception: ${JSON.stringify(e)}`) 
      } 
    }) 
  } 
} 
 
@Entry 
@Component 
struct NavigationExample2 { 
  private stack: NavPathStack = new NavPathStack(); 
  @State backStr: string = "暂无信息" 
 
  @Builder 
  PageMap(name: string) { 
    if (name === 'pageOne') { 
      PageOne() 
    } 
  } 
 
  build() { 
    Navigation(this.stack) { 
      Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center }) { 
        Text(this.backStr) 
        Button('pushPath', { stateEffect: true, type: ButtonType.Capsule }) 
          .width('80%') 
          .height(40) 
          .margin(20) 
          .onClick(() => { 
            let p = new PageParam(1); 
            this.stack.pushPath({ 
              name: "pageOne", param: p, onPop: (popInfo: PopInfo) => { 
                console.info(' result: ' + JSON.stringify(popInfo.result)); 
                this.backStr = popInfo.result['backStr'] as string 
              } 
            }) 
          }) 
      } 
      .width('100%') 
      .height('100%') 
    } 
    .width('100%') 
    .height('100%') 
    .navDestination(this.PageMap) 
    // .hideNavBar(true) 
    .title('Navigation') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进