#鸿蒙通关秘籍#如何在HarmonyOS NEXT中实现页面跳转时传递类对象?

HarmonyOS
6天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
云海迷踪SEM

在HarmonyOS NEXT中,使用Navigation实现页面跳转时,可以通过class-transformer插件来传递类对象,并调用对象的方法。以下是具体步骤:

  1. oh-package.json5中添加class-transformer插件的依赖:

    "dependencies": {
        "class-transformer": "^0.5.1"
    }
    
  2. 在页面中导入class-transformer库:

    import { plainToClass } from "class-transformer";
    
  3. 定义要传递的类,例如:

    export class UserBookingInfo {
        userName: string = '张山';
        userID: string = '332045199008120045';
        seatNo: string = '6A';
        constructor(name: string, id: string, seatNo: string) {
            this.userName = name;
            this.userID = id;
            this.seatNo = seatNo;
        }
        
        getUserInfo() {
            AlertDialog.show({ message: `用户信息为 姓名: ${this.userName}, 身份证号: ${this.userID}, 座位号: ${this.seatNo}`, alignment: DialogAlignment.Center});
        }
    }
    
  4. 将传递过来的参数通过class-transformer的plainToClass方法转化为类对象:

    let bookingString: string = this.pageStack.getParamByName('NavigationParameterTransfer')[0] as string;
    let userBookingTmp: UserBookingInfo = JSON.parse(bookingString);
    this.userBooking = plainToClass(UserBookingInfo, userBookingTmp);
    
分享
微博
QQ
微信
回复
6天前
相关问题