• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Page Routing (@ohos.router) (Not Recommended)
2
3
4Page routing refers to the redirection and data transfer between different pages in an application. It can be implemented through APIs of the **Router** module. Through different URLs, you can easily navigate users through pages. This document describes the functions provided by the **Router** module from the following aspects: [Page Redirection](#page-redirection), [Page Return](#page-return), [Adding a Confirmation Dialog Box Before Page Return](#adding-a-confirmation-dialog-box-before-page-return), and [Named Route](#named-route).
5
6>**NOTE**
7>
8>You are advised to use [Component Navigation (Navigation)](./arkts-navigation-navigation.md), which offers enhanced functionality and customization capabilities, as the routing framework in your application. For details about the differences between **Navigation** and **Router**, see [Transition from Router to Navigation](./arkts-router-to-navigation.md).
9
10## Page Redirection
11
12Page redirection is an important part of the development process. When using an application, you usually need to jump between different pages, and sometimes you need to pass data from one page to another.
13
14  **Figure 1** Page redirection
15![router-jump-to-detail](figures/router-jump-to-detail.gif)
16
17The **Router** module provides two redirection modes: [router.pushUrl](../reference/apis-arkui/js-apis-router.md#routerpushurl9) and [router.replaceUrl](../reference/apis-arkui/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used.
18
19- **router.pushUrl**: The target page is pushed into the page stack and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back](../reference/apis-arkui/js-apis-router.md#routerback) API.
20
21- **router.replaceUrl**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page.
22
23>**NOTE**
24>
25>- When creating a page, configure the route to this page by following instructions in <!--RP1-->[Building the Second Page](../quick-start/start-with-ets-stage.md#building-the-second-page)<!--RP1End-->.
26>
27>
28>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear](../reference/apis-arkui/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
29
30The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances.
31
32- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
33
34- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
35
36Before using the **Router** module, import it first.
37
38
39```ts
40import { promptAction, router } from '@kit.ArkUI';
41import { BusinessError } from '@kit.BasicServicesKit';
42```
43
44- Scenario 1: There is a home page (**Home**) and a details page (**Detail**). You want to click an offering on the home page to go to the details page. In addition, the home page needs to be retained in the page stack so that the status can be restored when the page is returned. In this scenario, you can use the **pushUrl** API and use the **Standard** instance mode (which can also be omitted).
45
46
47  ```ts
48  import { router } from '@kit.ArkUI';
49  // On the Home page
50  function onJumpClick(): void {
51    router.pushUrl({
52      url: 'pages/Detail' // Target URL.
53    }, router.RouterMode.Standard, (err) => {
54      if (err) {
55        console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
56        return;
57      }
58      console.info('Invoke pushUrl succeeded.');
59    });
60  }
61  ```
62
63  >**NOTE**
64  >
65  >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
66
67- Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl** API and use the Standard instance mode (which can also be omitted).
68
69
70  ```ts
71  import { router } from '@kit.ArkUI';
72  // On the Login page
73  function onJumpClick(): void {
74    router.replaceUrl({
75      url: 'pages/Profile' // Target URL.
76    }, router.RouterMode.Standard, (err) => {
77      if (err) {
78        console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`);
79        return;
80      }
81      console.info('Invoke replaceUrl succeeded.');
82    })
83  }
84  ```
85
86  >**NOTE**
87  >
88  >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
89
90- Scenario 3: There is a **Setting** page and a **Theme** page. After a theme option on the **Setting** page is clicked, the **Theme** page is displayed. Only one **Theme** page exists in the page stack at the same time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl** API and use the **Single** instance mode.
91
92
93  ```ts
94  import { router } from '@kit.ArkUI';
95  // On the Setting page
96  function onJumpClick(): void {
97    router.pushUrl({
98      url: 'pages/Theme' // Target URL.
99    }, router.RouterMode.Single, (err) => {
100      if (err) {
101        console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
102        return;
103      }
104      console.info('Invoke pushUrl succeeded.');
105    });
106  }
107  ```
108
109- Scenario 4: There is a search result list page (**SearchResult**) and a search result details page (**SearchDetail**). You want to click a result on the **SearchResult** page to go to the **SearchDetail** page. In addition, if the result has been viewed before, clicking the result displays the existing details page, instead of creating a new one. In this scenario, you can use the **replaceUrl** API and use the **Single** instance mode.
110
111
112  ```ts
113  import { router } from '@kit.ArkUI';
114
115  // On the SearchResult page
116  function onJumpClick(): void {
117    router.replaceUrl({
118      url: 'pages/SearchDetail' // Target URL.
119    }, router.RouterMode.Single, (err) => {
120      if (err) {
121        console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`);
122        return;
123      }
124      console.info('Invoke replaceUrl succeeded.');
125    })
126  }
127  ```
128
129The preceding scenarios do not involve parameter transfer.
130
131If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
132
133
134```ts
135import { router } from '@kit.ArkUI';
136class DataModelInfo {
137  age: number = 0;
138}
139
140class DataModel {
141  id: number = 0;
142  info: DataModelInfo|null = null;
143}
144
145function onJumpClick(): void {
146  // On the Home page
147  let paramsInfo: DataModel = {
148    id: 123,
149    info: {
150      age: 20
151    }
152  };
153
154  router.pushUrl({
155    url: 'pages/Detail', // Target URL.
156    params: paramsInfo // Add the params attribute to transfer custom parameters.
157  }, (err) => {
158    if (err) {
159      console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
160      return;
161    }
162    console.info('Invoke pushUrl succeeded.');
163  })
164}
165```
166
167On the target page, you can call the [getParams](../reference/apis-arkui/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example:
168
169
170```ts
171import { router } from '@kit.ArkUI';
172
173class InfoTmp {
174  age: number = 0
175}
176
177class RouTmp {
178  id: object = () => {
179  }
180  info: InfoTmp = new InfoTmp()
181}
182
183const params: RouTmp = router.getParams() as RouTmp; // Obtain the passed parameter object.
184const id: object = params.id // Obtain the value of the id attribute.
185const age: number = params.info.age // Obtain the value of the age attribute.
186```
187
188
189## Page Return
190
191Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process.
192
193  **Figure 2** Page return
194
195![router-back-to-home](figures/router-back-to-home.gif)
196
197Before using the **Router** module, import it first.
198
199
200```ts
201import { router } from '@kit.ArkUI';
202```
203
204You can use any of the following methods to return to a page:
205
206- Method 1: Return to the previous page.
207
208
209  ```ts
210  import { router } from '@kit.ArkUI';
211  router.back();
212  ```
213
214  This method allows you to return to the position of the previous page in the page stack. For this method to work, the previous page must exist in the page stack.
215
216- Method 2: Return to a specific page.
217
218
219  Return to the page through a common route.
220
221  ```ts
222  import { router } from '@kit.ArkUI';
223  router.back({
224    url: 'pages/Home'
225  });
226  ```
227
228  Return to the page through a named route.
229
230  ```ts
231  import { router } from '@kit.ArkUI';
232  router.back({
233    url: 'myPage' // myPage is the alias of the page to return to.
234  });
235  ```
236
237  This method allows users to return to a page with the specified path. For this method to work, the target page must exist in the page stack.
238
239- Method 3: Return to a specific page and pass custom parameters.
240
241
242  Return to the page through a common route.
243
244  ```ts
245  import { router } from '@kit.ArkUI';
246  router.back({
247    url: 'pages/Home',
248    params: {
249      info: 'From Home Page'
250    }
251  });
252  ```
253
254  Return to the page through a named route.
255
256  ```ts
257  import { router } from '@kit.ArkUI';
258  router.back({
259    url: 'myPage', // myPage is the alias of the page to return to.
260    params: {
261      info: 'From Home Page'
262    }
263  });
264  ```
265
266  This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams** API on the target page.
267
268On the target page, call the **router.getParams** API to obtain parameters at the desired location. For example, you can use it in the [onPageShow](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#onpageshow) lifecycle callback.
269
270
271```ts
272import { router } from '@kit.ArkUI';
273
274@Entry
275@Component
276struct Home {
277  @State message: string = 'Hello World';
278
279  onPageShow() {
280    const params = router.getParams() as Record<string, string>; // Obtain the passed parameter object.
281    if (params) {
282      const info: string = params.info as string; // Obtain the value of the info attribute.
283    }
284  }
285  ...
286}
287```
288
289>**NOTE**
290>
291>When the **router.back** API is used to return to a specified page, all pages between the top page (included) and the specified page (excluded) are pushed from the page stack and destroyed.
292>
293> If the **router.back** method is used to return to the original page, the original page will not be created repeatedly. Therefore, the variable declared using \@State will not be declared repeatedly, and the **aboutToAppear** lifecycle callback of the page will not be triggered. If you want to use the custom parameters transferred from the returned page on the original page, you can parse the parameters in the required position. For example, parameter parsing can be performed in the **onPageShow** lifecycle callback.
294
295
296## Adding a Confirmation Dialog Box Before Page Return
297
298During application development, to prevent misoperations or data loss, a dialog box needs to be displayed before a user returns from one page to another, asking the user whether to perform the operation.
299
300Such a dialog box can be in the [default style](#default-confirmation-dialog-box) or [custom style](#custom-confirmation-dialog-box).
301
302  **Figure 3** Adding a confirmation dialog box before page return
303
304![router-add-query-box-before-back](figures/router-add-query-box-before-back.gif)
305
306
307### Default Confirmation Dialog Box
308
309To implement this function, you can use the [router.showAlertBeforeBackPage](../reference/apis-arkui/js-apis-router.md#routershowalertbeforebackpage9) and [router.back](../reference/apis-arkui/js-apis-router.md#routerback) APIs provided by the **Router** module.
310
311Before using the **Router** module, import it first.
312
313
314```ts
315import { router } from '@kit.ArkUI';
316```
317
318To enable the confirmation dialog box for page return, call the [router.showAlertBeforeBackPage](../reference/apis-arkui/js-apis-router.md#routershowalertbeforebackpage9) API (for setting the information about the dialog box), then the [router.back](../reference/apis-arkui/js-apis-router.md#routerback) API. For example, define a click event processing function for the back button on the payment page:
319
320
321```ts
322import { router } from '@kit.ArkUI';
323import { BusinessError } from '@kit.BasicServicesKit';
324
325// Define a click event processing function for the back button.
326function onBackClick(): void {
327  // Invoke the router.showAlertBeforeBackPage() API to set the information about the confirmation dialog box.
328  try {
329    router.showAlertBeforeBackPage({
330      message: 'Payment not completed yet. Are you sure you want to return?' // Set the content of the confirmation dialog box.
331    });
332  } catch (err) {
333    let message = (err as BusinessError).message
334    let code = (err as BusinessError).code
335    console.error(`Invoke showAlertBeforeBackPage failed, code is ${code}, message is ${message}`);
336  }
337
338  // Invoke the router.back() API to return to the previous page.
339  router.back();
340}
341```
342
343The **router.showAlertBeforeBackPage** API receives an object as a parameter. The object contains the following attributes:
344
345**message**: content of the dialog box. The value is of the string type.
346If the API is called successfully, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
347
348When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects **Cancel**, the application stays on the current page. If the user selects OK, the **router.back** API is called and the redirection is performed based on the parameters.
349
350### Custom Confirmation Dialog Box
351
352To implement a custom confirmation dialog box, use APIs in the [promptAction.showDialog](../reference/apis-arkui/js-apis-promptAction.md#promptactionshowdialog) module or create a custom dialog box . This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box.
353
354Before using the **Router** module, import it first.
355
356
357```ts
358import { router } from '@kit.ArkUI';
359```
360
361In the event callback, call the [promptAction.showDialog](../reference/apis-arkui/js-apis-promptAction.md#promptactionshowdialog) API of the **PromptAction** module.
362
363
364```ts
365import { promptAction, router } from '@kit.ArkUI';
366import { BusinessError } from '@kit.BasicServicesKit';
367
368function onBackClick() {
369  // Display a custom confirmation dialog box.
370  promptAction.showDialog({
371    message:'Payment not completed yet. Are you sure you want to return?',
372    buttons: [
373      {
374        text: 'Cancel',
375        color: '#FF0000'
376      },
377      {
378        text: 'OK',
379        color: '#0099FF'
380      }
381    ]
382  }).then((result:promptAction.ShowDialogSuccessResponse) => {
383    if (result.index === 0) {
384      // The user selects Cancel.
385      console.info('User canceled the operation.');
386    } else if (result.index === 1) {
387      // The user selects OK.
388      console.info('User confirmed the operation.');
389      // Invoke the router.back() API to return to the previous page.
390      router.back();
391    }
392  }).catch((err:Error) => {
393    let message = (err as BusinessError).message
394    let code = (err as BusinessError).code
395    console.error(`Invoke showDialog failed, code is ${code}, message is ${message}`);
396  })
397}
398```
399
400When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects **Cancel**, the application stays on the current page. If the user selects OK, the **router.back** API is called and the redirection is performed based on the parameters.
401
402## Named Route
403
404To redirect to a page in a [HAR](../quick-start/har-package.md) or [HSP](../quick-start/in-app-hsp.md), you can use [router.pushNamedRoute](../reference/apis-arkui/js-apis-router.md#routerpushnamedroute10).
405
406  **Figure 4** Named route redirection
407
408![(figures/router-add-query-box-before-back.gif)](figures/namedroute-jump-to-mypage.gif)
409
410Before using the **Router** module, import it first.
411
412
413```ts
414import { router } from '@kit.ArkUI';
415```
416
417In the [HAR](../quick-start/har-package.md) or [HSP](../quick-start/in-app-hsp.md) you want to navigate to, name the @Entry decorated custom component in [EntryOptions](../quick-start/arkts-create-custom-components.md#entryoptions10).
418
419```ts
420// library/src/main/ets/pages/Index.ets
421// library is the custom name of the new shared package.
422@Entry({ routeName: 'myPage' })
423@Component
424export struct MyComponent {
425  build() {
426    Row() {
427      Column() {
428        Text('Library Page')
429          .fontSize(50)
430          .fontWeight(FontWeight.Bold)
431      }
432      .width('100%')
433    }
434    .height('100%')
435  }
436}
437```
438
439When the configuration is successful, import the named route page to the page from which you want to redirect.
440
441```ts
442import { router } from '@kit.ArkUI';
443import { BusinessError } from '@kit.BasicServicesKit';
444import '@ohos/library/src/main/ets/pages/Index';  // Import the named route page from the library of the shared package.
445@Entry
446@Component
447struct Index {
448  build() {
449    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
450      Text('Hello World')
451        .fontSize(50)
452        .fontWeight(FontWeight.Bold)
453        .margin({ top: 20 })
454        .backgroundColor('#ccc')
455        .onClick(() => { // Click to go to a page in another shared package.
456          try {
457            router.pushNamedRoute({
458              name: 'myPage',
459              params: {
460                data1: 'message',
461                data2: {
462                  data3: [123, 456, 789]
463                }
464              }
465            })
466          } catch (err) {
467            let message = (err as BusinessError).message
468            let code = (err as BusinessError).code
469            console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
470          }
471        })
472    }
473    .width('100%')
474    .height('100%')
475  }
476}
477```
478
479>**NOTE**
480>
481>To use the named route for redirection, you must configure dependencies in the **oh-package.json5** file of the application package. Example:
482>
483>```ts
484>"dependencies": {
485>    "@ohos/library": "file:../library",
486>    ...
487> }
488>```
489