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

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

1、设置云函数配置项

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

json 复制代码
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

2、查看函数名和版本

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

3、端侧调用云函数

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

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

python 复制代码
import type { BusinessError } from '@kit.BasicServicesKit';
import { cloudFunction } from '@kit.CloudFoundationKit';

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

javascript 复制代码
// 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属性获取。

ini 复制代码
let resultValue = value.result;

4、完整代码

typescript 复制代码
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%')
  }
}
相关推荐
passerby60617 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅8 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅8 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊9 小时前
jwt介绍
前端
爱敲代码的小鱼9 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte9 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc