当前位置: 首页 > ds >正文

HarmonyOS NEXT端侧工程调用云侧能力实现业务功能

完成云侧云函数开发、调试、部署之后,接下来就是端侧调用云函数获取数据,实现真正意义上的端云协同开发。

1、设置云函数配置项

端侧调用云函数需要网络环境,因此,需要在“entry/src/main/module.json5”文件中添加网络权限。

"requestPermissions": [{"name": "ohos.permission.INTERNET"}
]

2、查看函数名和版本

在函数的触发器页面点击“HTTP触发器”,查看“触发URL”的后缀,获取触发器的标识,格式为“函数名-版本号”。如下图所示,“calculate-baby-age-$latest”即为HTTP触发器标识,其中“calculate-baby-age”为函数名,“$latest”为版本号。

image-20250622214613220

3、端侧调用云函数

在端侧工程(Application)模块entry目录下打开src/main/ets/pages > Index.ets页面使用使用搜索框组件Search和日期弹窗CalendarPickerDialog实现宝宝出生日期选择,并根据选择的日期调用计算宝宝的年龄云函数返回包含年、月、日、天数的宝宝年龄信息,具体调用云函数步骤如下所示:

1)在项目中导入云函数组件cloudFunction。

import type { BusinessError } from '@kit.BasicServicesKit';
import { cloudFunction } from '@kit.CloudFoundationKit';

2)调用call()方法设置函数,在方法中传入函数名称,返回调用结果。

// Promise异步回调
function callFunctionPromise() {cloudFunction.call({name: 'calculate-baby-age', // functionName需替换成指定的函数名version: '$latest',   // 如果不传入版本号,默认为“$latest”。timeout: 10 * 1000,   // 单位为毫秒,默认为70*1000毫秒。data: {               // data为云函数接收的入参birthday: '2023-3-15'}}).then((value: cloudFunction.FunctionResult) => {hilog.info(0x0000, 'testTag', `Succeeded in calling the function, result: ${JSON.stringify(value.result)}`);}).catch((err: BusinessError) => {hilog.error(0x0000, 'testTag', `Failed to call the function, code: ${err.code}, message: ${err.message}`);});
}// callback异步调用
function callFunctionCallback() {cloudFunction.call({name: 'calculate-baby-age',version: '$latest',timeout: 10 * 1000,data: {birthday: '2023-3-15'}}, (err: BusinessError, value: cloudFunction.FunctionResult) => {if (err) {hilog.error(0x0000, 'testTag', `Failed to call the function, code: ${err.code}, message: ${err.message}`);return;}hilog.info(0x0000, 'testTag', `Succeeded in calling the function, result: ${JSON.stringify(value.result)}`);});
}

3)如果需要关注函数的返回值,可调用result属性获取。

let resultValue = value.result;

4、完整代码

import type { BusinessError } from '@kit.BasicServicesKit';
import { cloudFunction } from '@kit.CloudFoundationKit';interface BabyAge {years: number;months: number;days: number;totalDays: number;
}interface ResponseBody {code: number;desc: string;data: BabyAge
}@Entry
@Component
struct Index {controller: SearchController = new SearchController();@State birthday: string = "";@State callFunctionResult: BabyAge | undefined = undefined;build() {Column({ space: 10 }) {Search({ controller: this.controller, value: this.birthday }).width('90%').height('54vp').searchIcon(new SymbolGlyphModifier($r('sys.symbol.calendar_badge_play')).fontColor([Color.Blue]).fontSize('30fp')).cancelButton({style: CancelButtonStyle.INVISIBLE}).borderRadius('8vp').onClick(() => {CalendarPickerDialog.show({selected: new Date(this.birthday),acceptButtonStyle: {style: ButtonStyleMode.EMPHASIZED},cancelButtonStyle: {fontColor: Color.Grey},onAccept: async (value) => {console.info("calendar onAccept:" + JSON.stringify(value))let result: cloudFunction.FunctionResult = await cloudFunction.call({name: 'calculate-baby-age',version: '$latest',timeout: 10 * 1000,data: {birthday: value}});let body = result.result as ResponseBody;this.callFunctionResult = body.data;}})})if (this.callFunctionResult !== undefined) {Text(`我已经${this.callFunctionResult.years}岁了 ${this.callFunctionResult.months}${this.callFunctionResult.days}天了~`)Text(`我已经出生${this.callFunctionResult.totalDays}天了~`)}}.width('100%').height('100%')}
}
http://www.xdnf.cn/news/14757.html

相关文章:

  • 跨个体预训练与轻量化Transformer在手势识别中的应用:Bioformer
  • 什么是跨域问题?后端如何解决跨域问题?
  • rent8_wechat-最常用出租屋管理系统-微信小程序
  • 计算机网络第九章——数据链路层《流量控制和可靠传输》
  • Web攻防-XSS跨站Cookie盗取数据包提交网络钓鱼BEEF项目XSS平台危害利用
  • 【分布式理论】读确认数与写确认数:分布式一致性的核心概念
  • 吴恩达:从斯坦福到 Coursera,他的深度学习布道之路
  • Solidity内部合约创建全解析:解锁Web3开发新姿势
  • Qt/C++应用:防御性编程完全指南
  • 车载电子电器架构 --- 电子电气架构设计方案
  • Android Studio 打 APK 包报错 Invalid keystore format 的解决方法
  • 【价值链】产品经理
  • Python编程语言:2025年AI浪潮下的技术统治与学习红利
  • 成长笔记——多串口发送与接收
  • mysql导入大sql(比如10GB的sql文件)
  • 一站式了解责任链模式
  • c++ 虚继承
  • C# 将 Enum枚举转成List,并显示在下拉列表中
  • 加密货币:比特币
  • Python中布尔值在函数中的巧妙运用
  • 单片机开发日志cv MDK-ARM工具链迁移到MAKE
  • 自动化性能回退机制——蓝绿部署与灰度发布
  • Python 中设置布尔值参数为 True 来启用验证
  • 分布式系统中的 Kafka:流量削峰与异步解耦(二)
  • 「Linux文件及目录管理」硬链接与软连接
  • Spring WebFlux和Spring MVC的对比
  • AR 眼镜之-条形码识别-实现方案
  • Lua 事务双写、RedisGears 异步双写、零停机索引迁移与容量预估
  • PLuTo 编译器示例17-20
  • Unix、Linux、POSIX、Minix 区别与联系