文档管理中心
指南开发第一个元服务构建元服务页面

构建元服务页面

下面我们将构建元服务的两个页面,并按预定的业务逻辑,实现页面间跳转。

构建元服务的第一个页面

  1. 使用文本组件。

    工程同步完成后,在“Project”窗口,单击“entry > src > main > ets > pages”,打开“Index.ets”文件,可以看到页面由Text组件组成。

    针对本文中使用文本/按钮来实现页面跳转/返回的应用场景,页面均使用RowColumn组件来构建布局。对于更多复杂元素对齐的场景,可选择使用RelativeContainer组件进行布局。

  2. 创建导航首页。

    使用Navigation创建导航主页,并创建导航控制器NavPathStack以此来实现不同页面之间的跳转。

    Index.ets”文件的示例如下:

    收起
    自动换行
    深色代码主题
    复制
    1. import { authentication } from '@kit.AccountKit';
    2. import { BusinessError } from '@kit.BasicServicesKit';
    3. import { hilog } from '@kit.PerformanceAnalysisKit';
    4. @Entry
    5. @Component
    6. struct NavigationDemo {
    7. @Provide('pathInfos') pathInfos: NavPathStack = new NavPathStack();
    8. @State message: string = 'Hello World'
    9. build() {
    10. Column() {
    11. Navigation(this.pathInfos) {
    12. Column() {
    13. Text(this.message)
    14. .fontSize(50)
    15. .fontWeight(FontWeight.Bold)
    16. }
    17. .width('100%')
    18. .height('100%')
    19. .justifyContent(FlexAlign.Center)
    20. .alignItems(HorizontalAlign.Center)
    21. }
    22. .width('100%')
    23. .mode(NavigationMode.Auto)
    24. }
    25. .size({ width: '100%', height: '100%' })
    26. .backgroundColor(0xf4f4f5)
    27. }
    28. aboutToAppear() {
    29. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    30. this.loginWithHuaweiID();
    31. }
    32. /**
    33. * Sample code for using HUAWEI ID to log in to atomic service.
    34. * According to the Atomic Service Review Guide, when an atomic service has an account system,
    35. * the option to log in with a HUAWEI ID must be provided.
    36. * The following presets the atomic service to use the HUAWEI ID silent login function.
    37. * To enable the atomic service to log in successfully using the HUAWEI ID, please refer
    38. * to the HarmonyOS HUAWEI ID Access Guide to configure the client ID and fingerprint certificate.
    39. */
    40. private loginWithHuaweiID() {
    41. // Create a login request and set parameters
    42. let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    43. // Whether to forcibly launch the HUAWEI ID login page when the user is not logged in with the HUAWEI ID
    44. loginRequest.forceLogin = false;
    45. // Execute login request
    46. let controller = new authentication.AuthenticationController();
    47. controller.executeRequest(loginRequest).then((data) => {
    48. let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
    49. let authCode = loginWithHuaweiIDResponse.data?.authorizationCode;
    50. // Send authCode to the backend in exchange for unionID, session
    51. }).catch((error: BusinessError) => {
    52. hilog.error(0x0000, 'testTag', 'error: %{public}s', JSON.stringify(error));
    53. if (error.code == authentication.AuthenticationErrorCode.ACCOUNT_NOT_LOGGED_IN) {
    54. // HUAWEI ID is not logged in, it is recommended to jump to the login guide page
    55. }
    56. });
    57. }
    58. }
  3. 添加按钮。

    在默认页面基础上,我们添加一个Button组件。“Index.ets”文件的示例如下:
    收起
    自动换行
    深色代码主题
    复制
    1. import { authentication } from '@kit.AccountKit';
    2. import { BusinessError } from '@kit.BasicServicesKit';
    3. import { hilog } from '@kit.PerformanceAnalysisKit';
    4. @Entry
    5. @Component
    6. struct NavigationDemo {
    7. @Provide('pathInfos') pathInfos: NavPathStack = new NavPathStack();
    8. @State message: string = 'Hello World'
    9. build() {
    10. Column() {
    11. Navigation(this.pathInfos) {
    12. Column() {
    13. Text(this.message)
    14. .fontSize(50)
    15. .fontWeight(FontWeight.Bold)
    16. // 添加按钮,以响应用户点击
    17. Button() {
    18. Text('Next')
    19. .fontSize(30)
    20. .fontWeight(FontWeight.Bold)
    21. }
    22. .type(ButtonType.Capsule)
    23. .margin({ top: 20 })
    24. .backgroundColor('#0D9FFB')
    25. .width('40%')
    26. .height('5%')
    27. }
    28. .width('100%')
    29. .height('100%')
    30. .justifyContent(FlexAlign.Center)
    31. .alignItems(HorizontalAlign.Center)
    32. }
    33. .width('100%')
    34. .mode(NavigationMode.Auto)
    35. }
    36. .size({ width: '100%', height: '100%' })
    37. .backgroundColor(0xf4f4f5)
    38. }
    39. aboutToAppear() {
    40. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    41. this.loginWithHuaweiID();
    42. }
    43. /**
    44. * Sample code for using HUAWEI ID to log in to atomic service.
    45. * According to the Atomic Service Review Guide, when an atomic service has an account system,
    46. * the option to log in with a HUAWEI ID must be provided.
    47. * The following presets the atomic service to use the HUAWEI ID silent login function.
    48. * To enable the atomic service to log in successfully using the HUAWEI ID, please refer
    49. * to the HarmonyOS HUAWEI ID Access Guide to configure the client ID and fingerprint certificate.
    50. */
    51. private loginWithHuaweiID() {
    52. // Create a login request and set parameters
    53. let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    54. // Whether to forcibly launch the HUAWEI ID login page when the user is not logged in with the HUAWEI ID
    55. loginRequest.forceLogin = false;
    56. // Execute login request
    57. let controller = new authentication.AuthenticationController();
    58. controller.executeRequest(loginRequest).then((data) => {
    59. let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
    60. let authCode = loginWithHuaweiIDResponse.data?.authorizationCode;
    61. // Send authCode to the backend in exchange for unionID, session
    62. }).catch((error: BusinessError) => {
    63. hilog.error(0x0000, 'testTag', 'error: %{public}s', JSON.stringify(error));
    64. if (error.code == authentication.AuthenticationErrorCode.ACCOUNT_NOT_LOGGED_IN) {
    65. // HUAWEI ID is not logged in, it is recommended to jump to the login guide page
    66. }
    67. });
    68. }
    69. }
  4. 将真机与电脑连接。具体指导及要求,请参见运行应用/服务,第一个页面效果如下图所示。

构建元服务的第二个页面

  1. 创建第二个页面。

    • 新建第二个页面文件。在“Project”窗口,打开“entry > src > main > ets”,右键单击“pages”文件夹,选择“New > ArkTS File”,命名为“Second”,回车。可以看到文件目录结构如下所示。

    • 配置第二个页面的路由。在“Project”窗口,打开“entry > src > main > resources > base > profile”,新增router_map.json文件对"routerMap"进行配置,示例如下:

      收起
      自动换行
      深色代码主题
      复制
      1. {
      2. "routerMap" : [
      3. {
      4. "name" : "second",
      5. "pageSourceFile" : "src/main/ets/pages/Second.ets",
      6. "buildFunction" : "PageSecondBuilder"
      7. }
      8. ]
      9. }

      在module.json5文件中新增"routerMap"配置,并将其地址配置为路由表位置。

      收起
      自动换行
      深色代码主题
      复制
      1. "routerMap": "$profile:router_map"
  2. 添加文本及按钮。

    参照第一个页面,在第二个页面添加Text组件、Button组件等,并设置其样式。

    使用NavDestination创建导航子页。创建导航控制器NavPathStack并在onReady时进行初始化,获取当前所在的导航控制器,以此来实现不同页面之间的跳转。

    Second.ets”文件的示例如下:

    收起
    自动换行
    深色代码主题
    复制
    1. // Second.ets
    2. @Builder
    3. export function PageSecondBuilder() {
    4. PageSecond();
    5. }
    6. @Component
    7. export struct PageSecond {
    8. pathInfos: NavPathStack = new NavPathStack();
    9. @State message: string = 'Hi there';
    10. build() {
    11. Row() {
    12. NavDestination() {
    13. Column() {
    14. Text(this.message)
    15. .fontSize(50)
    16. .fontWeight(FontWeight.Bold)
    17. Button() {
    18. Text('Back')
    19. .fontSize(30)
    20. .fontWeight(FontWeight.Bold)
    21. }
    22. .type(ButtonType.Capsule)
    23. .margin({ top: 20 })
    24. .backgroundColor('#0D9FFB')
    25. .width('40%')
    26. .height('7%')
    27. }
    28. .width('100%')
    29. .height('75%')
    30. .justifyContent(FlexAlign.Center)
    31. .alignItems(HorizontalAlign.Center)
    32. }
    33. .width('100%')
    34. .onReady((ctx: NavDestinationContext) => {
    35. this.pathInfos = ctx.pathStack;
    36. });
    37. }
    38. .size({ width: '100%', height: '100%' })
    39. .backgroundColor(0xf4f4f5)
    40. }
    41. }

实现页面间的跳转

页面间的导航可以通过组件导航(Navigation)来实现。推荐使用NavPathStack实现页面路由跳转。

对Button组件添加onClick方法,并在其中使用导航控制器NavPathStack的pushPathByName方法,使组件可以在点击之后从当前页面跳转到输入参数name在路由表内对应的页面。

  1. 第一个页面跳转到第二个页面。

    在第一个页面中,跳转按钮绑定onClick事件,点击按钮时跳转到第二页。“Index.ets”文件的示例如下:

    收起
    自动换行
    深色代码主题
    复制
    1. import { authentication } from '@kit.AccountKit';
    2. import { BusinessError } from '@kit.BasicServicesKit';
    3. import { hilog } from '@kit.PerformanceAnalysisKit';
    4. @Entry
    5. @Component
    6. struct NavigationDemo {
    7. @Provide('pathInfos') pathInfos: NavPathStack = new NavPathStack();
    8. @State message: string = 'Hello World'
    9. build() {
    10. Column() {
    11. Navigation(this.pathInfos) {
    12. Column() {
    13. Text(this.message)
    14. .fontSize(50)
    15. .fontWeight(FontWeight.Bold)
    16. // 添加按钮,以响应用户点击
    17. Button() {
    18. Text('Next')
    19. .fontSize(30)
    20. .fontWeight(FontWeight.Bold)
    21. }
    22. .type(ButtonType.Capsule)
    23. .margin({ top: 20 })
    24. .backgroundColor('#0D9FFB')
    25. .width('40%')
    26. .height('5%')
    27. .onClick(() => {
    28. this.pathInfos.pushPathByName('second', 'custom_param');
    29. })
    30. }
    31. .width('100%')
    32. .height('100%')
    33. .justifyContent(FlexAlign.Center)
    34. .alignItems(HorizontalAlign.Center)
    35. }
    36. .width('100%')
    37. .mode(NavigationMode.Auto)
    38. }
    39. .size({ width: '100%', height: '100%' })
    40. .backgroundColor(0xf4f4f5)
    41. }
    42. aboutToAppear() {
    43. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    44. this.loginWithHuaweiID();
    45. }
    46. /**
    47. * Sample code for using HUAWEI ID to log in to atomic service.
    48. * According to the Atomic Service Review Guide, when an atomic service has an account system,
    49. * the option to log in with a HUAWEI ID must be provided.
    50. * The following presets the atomic service to use the HUAWEI ID silent login function.
    51. * To enable the atomic service to log in successfully using the HUAWEI ID, please refer
    52. * to the HarmonyOS HUAWEI ID Access Guide to configure the client ID and fingerprint certificate.
    53. */
    54. private loginWithHuaweiID() {
    55. // Create a login request and set parameters
    56. let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    57. // Whether to forcibly launch the HUAWEI ID login page when the user is not logged in with the HUAWEI ID
    58. loginRequest.forceLogin = false;
    59. // Execute login request
    60. let controller = new authentication.AuthenticationController();
    61. controller.executeRequest(loginRequest).then((data) => {
    62. let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
    63. let authCode = loginWithHuaweiIDResponse.data?.authorizationCode;
    64. // Send authCode to the backend in exchange for unionID, session
    65. }).catch((error: BusinessError) => {
    66. hilog.error(0x0000, 'testTag', 'error: %{public}s', JSON.stringify(error));
    67. if (error.code == authentication.AuthenticationErrorCode.ACCOUNT_NOT_LOGGED_IN) {
    68. // HUAWEI ID is not logged in, it is recommended to jump to the login guide page
    69. }
    70. });
    71. }
    72. }
  2. 第二个页面返回到第一个页面。

    在第二个页面中,返回按钮绑定onClick事件,并在其中使用导航控制器NavPathStack的pop方法,使组件可以在点击之后弹出路由栈栈顶元素实现页面的返回。点击按钮时返回到第一页。

    Second.ets”文件的示例如下:

    收起
    自动换行
    深色代码主题
    复制
    1. // Second.ets
    2. @Builder
    3. export function PageSecondBuilder() {
    4. PageSecond();
    5. }
    6. @Component
    7. export struct PageSecond {
    8. pathInfos: NavPathStack = new NavPathStack();
    9. @State message: string = 'Hi there';
    10. build() {
    11. Row() {
    12. NavDestination() {
    13. Column() {
    14. Text(this.message)
    15. .fontSize(50)
    16. .fontWeight(FontWeight.Bold)
    17. Button() {
    18. Text('Back')
    19. .fontSize(30)
    20. .fontWeight(FontWeight.Bold)
    21. }
    22. .type(ButtonType.Capsule)
    23. .margin({ top: 20 })
    24. .backgroundColor('#0D9FFB')
    25. .width('40%')
    26. .height('7%')
    27. .onClick(() => {
    28. this.pathInfos.pop(); // 返回上一页
    29. })
    30. }
    31. .width('100%')
    32. .height('75%')
    33. .justifyContent(FlexAlign.Center)
    34. .alignItems(HorizontalAlign.Center)
    35. }
    36. .width('100%')
    37. .onReady((ctx: NavDestinationContext) => {
    38. this.pathInfos = ctx.pathStack;
    39. });
    40. }
    41. .size({ width: '100%', height: '100%' })
    42. .backgroundColor(0xf4f4f5)
    43. }
    44. }
  3. 效果如下图所示:

在 指南 中进行搜索
请输入您想要搜索的关键词