管理中心
我的
工具开发工具DevEco Studio(Windows/macOS版)开发环境搭建工程创建模块管理端云一体化开发开发端云工程开发端侧工程在端侧调用云侧代码在端侧调用云函数

在端侧调用云函数

前提条件

请确保云函数已正确开发并部署。

操作步骤

  1. 在代码文件中引入Cloud Foundation Kit。
    收起
    自动换行
    深色代码主题
    复制
    1. import { cloudFunction } from '@kit.CloudFoundationKit'
    2. import { BusinessError } from '@kit.BasicServicesKit';
  2. 调用您云侧部署的云函数。关于云函数接口的更详细信息,请参考Cloud Foundation Kit API参考-云函数模块。
    收起
    自动换行
    深色代码主题
    复制
    1. //填入需要调用的云函数名称
    2. cloudFunction.call({name: 'xxxx'})
    3. .then((res: cloudFunction.FunctionResult) => {
    4. // 处理调用返回
    5. }).catch((err: BusinessError) => {
    6. // 调用云函数异常时的处理逻辑
    7. })

    例如,调用云侧函数“my-cloud-function”,以返回一个时间戳。

    收起
    自动换行
    深色代码主题
    复制
    1. import { cloudFunction } from '@kit.CloudFoundationKit';
    2. import { BusinessError } from '@kit.BasicServicesKit';
    3. interface result {
    4. intervalTime: number
    5. }
    6. interface res {
    7. result: result
    8. }
    9. @Entry
    10. @Component
    11. struct CloudFunction {
    12. @State globalId: string = '';
    13. build() {
    14. Column() {
    15. Navigation()
    16. .title($r('app.string.cloud_function_title'))
    17. .height('50vp')
    18. .width('100%')
    19. .margin({ bottom: 10 })
    20. .titleMode(NavigationTitleMode.Mini)
    21. Text($r('app.string.cloud_function_description'))
    22. .width('90%')
    23. .textAlign(TextAlign.Center)
    24. .margin({ top: 20, bottom: 20 })
    25. .fontSize($r('app.float.body_font_size'))
    26. Button({ type: ButtonType.Normal }) {
    27. Text($r('app.string.cloud_function_button_text'))
    28. .fontColor($r('app.color.white'))
    29. .margin({ top: 5, bottom: 5 })
    30. }
    31. .width('90%')
    32. .borderRadius('8vp')
    33. .height('30vp')
    34. .margin({ top: 10 })
    35. .onClick(() => {
    36. this.callMyFunction()
    37. })
    38. Column() {
    39. Text(this.globalId).fontSize($r('app.float.body_font_size'))
    40. }
    41. .width('90%')
    42. .padding({ top: 20, bottom: 20 })
    43. .margin({ top: 20 })
    44. .backgroundColor($r('app.color.placeholder_background'))
    45. }.height('100%')
    46. }
    47. callMyFunction() {
    48. cloudFunction.call({ name: 'my-cloud-function' }).then((res: cloudFunction.FunctionResult) => {
    49. let callback = res as res;
    50. console.info(`Succeeded in call the function, time:${callback.result.intervalTime} `);
    51. }).catch((err: BusinessError) => {
    52. console.error(`Failed to call the function, Code: ${err.code}, message: ${err.message}`);
    53. });
    54. }
    55. }