1# Page Routing (@ohos.router) (Not Recommended) 2 3Page 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 outlines the key features of the **Router** module, including: 4 5- [Page Redirection](#page-redirection) 6- [Page Return](#page-return) 7- [Adding a Confirmation Dialog Box Before Page Return](#adding-a-confirmation-dialog-box-before-page-return) 8- [Named Route](#named-route) 9 10>**NOTE** 11> 12>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). 13 14## Page Redirection 15 16Page 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. 17 18 **Figure 1** Page redirection 19 20 21The **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. 22 23- **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. 24 25- **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. 26 27>**NOTE** 28> 29>- 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-->. 30> 31> 32>- 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. 33 34The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances. 35 36- **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. 37 38- **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. 39 40Before using the **Router** module, import it first. 41 42 43```ts 44import { promptAction, router } from '@kit.ArkUI'; 45import { BusinessError } from '@kit.BasicServicesKit'; 46``` 47 48- 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). 49 50 ```ts 51 import { router } from '@kit.ArkUI'; 52 53 // On the Home page 54 function onJumpClick(): void { 55 router.pushUrl({ 56 url: 'pages/Detail' // Target URL. 57 }, router.RouterMode.Standard, (err) => { 58 if (err) { 59 console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`); 60 return; 61 } 62 console.info('Invoke pushUrl succeeded.'); 63 }); 64 } 65 ``` 66 67 >**NOTE** 68 > 69 >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. 70 71- 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). 72 73 ```ts 74 import { router } from '@kit.ArkUI'; 75 76 // On the Login page 77 function onJumpClick(): void { 78 router.replaceUrl({ 79 url: 'pages/Profile' // Target URL. 80 }, router.RouterMode.Standard, (err) => { 81 if (err) { 82 console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`); 83 return; 84 } 85 console.info('Invoke replaceUrl succeeded.'); 86 }) 87 } 88 ``` 89 90 >**NOTE** 91 > 92 >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted. 93 94- 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. 95 96 ```ts 97 import { router } from '@kit.ArkUI'; 98 99 // On the Setting page 100 function onJumpClick(): void { 101 router.pushUrl({ 102 url: 'pages/Theme' // Target URL. 103 }, router.RouterMode.Single, (err) => { 104 if (err) { 105 console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`); 106 return; 107 } 108 console.info('Invoke pushUrl succeeded.'); 109 }); 110 } 111 ``` 112 113- 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. 114 115 ```ts 116 import { router } from '@kit.ArkUI'; 117 118 // On the SearchResult page 119 function onJumpClick(): void { 120 router.replaceUrl({ 121 url: 'pages/SearchDetail' // Target URL. 122 }, router.RouterMode.Single, (err) => { 123 if (err) { 124 console.error(`Invoke replaceUrl failed, code is ${err.code}, message is ${err.message}`); 125 return; 126 } 127 console.info('Invoke replaceUrl succeeded.'); 128 }) 129 } 130 ``` 131 132The preceding scenarios do not involve parameter transfer. 133 134If 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: 135 136 137```ts 138import { router } from '@kit.ArkUI'; 139 140class DataModelInfo { 141 age: number = 0; 142} 143 144class DataModel { 145 id: number = 0; 146 info: DataModelInfo | null = null; 147} 148 149function onJumpClick(): void { 150 // On the Home page 151 let paramsInfo: DataModel = { 152 id: 123, 153 info: { 154 age: 20 155 } 156 }; 157 158 router.pushUrl({ 159 url: 'pages/Detail', // Target URL. 160 params: paramsInfo // Add the params attribute to transfer custom parameters. 161 }, (err) => { 162 if (err) { 163 console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`); 164 return; 165 } 166 console.info('Invoke pushUrl succeeded.'); 167 }) 168} 169``` 170 171On 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: 172 173 174```ts 175import { router } from '@kit.ArkUI'; 176 177class InfoTmp { 178 age: number = 0 179} 180 181class RouTmp { 182 id: object = () => { 183 } 184 info: InfoTmp = new InfoTmp() 185} 186 187const params: RouTmp = router.getParams() as RouTmp; // Obtain the passed parameter object. 188const id: object = params.id // Obtain the value of the id attribute. 189const age: number = params.info.age // Obtain the value of the age attribute. 190``` 191 192 193## Page Return 194 195Implement 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. 196 197 **Figure 2** Page return 198 199 200 201Before using the **Router** module, import it first. 202 203 204```ts 205import { router } from '@kit.ArkUI'; 206``` 207 208You can use any of the following methods to return to a page: 209 210- Method 1: Return to the previous page. 211 212 213 ```ts 214 import { router } from '@kit.ArkUI'; 215 216 router.back(); 217 ``` 218 219 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. 220 221- Method 2: Return to a specific page. 222 223 224 Return to the page through a common route. 225 226 ```ts 227 import { router } from '@kit.ArkUI'; 228 229 router.back({ 230 url: 'pages/Home' 231 }); 232 ``` 233 234 Return to the page through a named route. 235 236 ```ts 237 import { router } from '@kit.ArkUI'; 238 239 router.back({ 240 url: 'myPage' // myPage is the alias of the page to return to. 241 }); 242 ``` 243 244 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. 245 246- Method 3: Return to a specific page and pass custom parameters. 247 248 249 Return to the page through a common route. 250 251 ```ts 252 import { router } from '@kit.ArkUI'; 253 254 router.back({ 255 url: 'pages/Home', 256 params: { 257 info: 'From Home Page' 258 } 259 }); 260 ``` 261 262 Return to the page through a named route. 263 264 ```ts 265 import { router } from '@kit.ArkUI'; 266 267 router.back({ 268 url: 'myPage', // myPage is the alias of the page to return to. 269 params: { 270 info: 'From Home Page' 271 } 272 }); 273 ``` 274 275 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. 276 277On 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. 278 279> **NOTE** 280> 281> To avoid confusion with **router** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](../reference/apis-arkui/js-apis-arkui-UIContext.md#uicontext) API, and then obtain the **router** instance bound to the context through the [getRouter](../reference/apis-arkui/js-apis-arkui-UIContext.md#getrouter) API. 282 283```ts 284@Entry 285@Component 286struct Home { 287 @State message: string = 'Hello World'; 288 289 onPageShow() { 290 const params = this.getUIContext().getRouter().getParams() as Record<string, string>; // Obtain the passed parameter object. 291 if (params) { 292 const info: string = params.info as string; // Obtain the value of the info attribute. 293 } 294 } 295 296 ... 297} 298``` 299 300>**NOTE** 301> 302>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. 303> 304> 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. 305 306 307## Adding a Confirmation Dialog Box Before Page Return 308 309During 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. 310 311Such a dialog box can be in the [default style](#default-confirmation-dialog-box) or [custom style](#custom-confirmation-dialog-box). 312 313 **Figure 3** Adding a confirmation dialog box before page return 314 315 316 317 318### Default Confirmation Dialog Box 319 320To 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. 321 322Before using the **Router** module, import it first. 323 324 325```ts 326import { router } from '@kit.ArkUI'; 327``` 328 329To 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: 330 331```ts 332import { router } from '@kit.ArkUI'; 333import { BusinessError } from '@kit.BasicServicesKit'; 334 335// Define a click event processing function for the back button. 336function onBackClick(): void { 337 // Invoke the router.showAlertBeforeBackPage() API to set the information about the confirmation dialog box. 338 try { 339 router.showAlertBeforeBackPage({ 340 message: 'Payment not completed yet. Are you sure you want to return?' // Set the content of the confirmation dialog box. 341 }); 342 } catch (err) { 343 let message = (err as BusinessError).message 344 let code = (err as BusinessError).code 345 console.error(`Invoke showAlertBeforeBackPage failed, code is ${code}, message is ${message}`); 346 } 347 348 // Invoke the router.back() API to return to the previous page. 349 router.back(); 350} 351``` 352 353The **router.showAlertBeforeBackPage** API receives an object as a parameter. The object contains the following attributes: 354 355**message**: content of the dialog box. The value is of the string type. 356If 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**. 357 358When 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. 359 360### Custom Confirmation Dialog Box 361 362To 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. 363 364Before using the **Router** module, import it first. 365 366 367```ts 368import { router } from '@kit.ArkUI'; 369``` 370 371In the event callback, call the [promptAction.showDialog](../reference/apis-arkui/js-apis-promptAction.md#promptactionshowdialog) API of the **PromptAction** module. 372 373```ts 374import { promptAction, router } from '@kit.ArkUI'; 375import { BusinessError } from '@kit.BasicServicesKit'; 376 377function onBackClick() { 378 // Display a custom confirmation dialog box. 379 promptAction.showDialog({ 380 message:'Payment not completed yet. Are you sure you want to return?', 381 buttons: [ 382 { 383 text: 'Cancel', 384 color: '#FF0000' 385 }, 386 { 387 text: 'OK', 388 color: '#0099FF' 389 } 390 ] 391 }).then((result: promptAction.ShowDialogSuccessResponse) => { 392 if (result.index === 0) { 393 // The user selects Cancel. 394 console.info('User canceled the operation.'); 395 } else if (result.index === 1) { 396 // The user selects OK. 397 console.info('User confirmed the operation.'); 398 // Invoke the router.back() API to return to the previous page. 399 router.back(); 400 } 401 }).catch((err: Error) => { 402 let message = (err as BusinessError).message 403 let code = (err as BusinessError).code 404 console.error(`Invoke showDialog failed, code is ${code}, message is ${message}`); 405 }) 406} 407``` 408 409When 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. 410 411## Named Route 412 413To 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). 414 415 **Figure 4** Named route redirection 416 417 418 419Before using the **Router** module, import it first. 420 421 422```ts 423import { router } from '@kit.ArkUI'; 424``` 425 426In 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). 427 428```ts 429// library/src/main/ets/pages/Index.ets 430// library is the custom name of the new shared package. 431@Entry({ routeName: 'myPage' }) 432@Component 433export struct MyComponent { 434 build() { 435 Row() { 436 Column() { 437 Text('Library Page') 438 .fontSize(50) 439 .fontWeight(FontWeight.Bold) 440 } 441 .width('100%') 442 } 443 .height('100%') 444 } 445} 446``` 447 448When the configuration is successful, import the named route page to the page from which you want to redirect. 449 450```ts 451import { BusinessError } from '@kit.BasicServicesKit'; 452import '@ohos/library/src/main/ets/pages/Index'; // Import the named route page from the library of the shared package. 453 454@Entry 455@Component 456struct Index { 457 build() { 458 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 459 Text('Hello World') 460 .fontSize(50) 461 .fontWeight(FontWeight.Bold) 462 .margin({ top: 20 }) 463 .backgroundColor('#ccc') 464 .onClick(() => { // Click to go to a page in another shared package. 465 try { 466 this.getUIContext().getRouter().pushNamedRoute({ 467 name: 'myPage', 468 params: { 469 data1: 'message', 470 data2: { 471 data3: [123, 456, 789] 472 } 473 } 474 }) 475 } catch (err) { 476 let message = (err as BusinessError).message 477 let code = (err as BusinessError).code 478 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 479 } 480 }) 481 } 482 .width('100%') 483 .height('100%') 484 } 485} 486``` 487 488>**NOTE** 489> 490>To use the named route for redirection, you must configure dependencies in the **oh-package.json5** file of the application package. Example: 491> 492>```ts 493>"dependencies": { 494> "@ohos/library": "file:../library", 495> ... 496> } 497>``` 498