Navigation-related routing operations are all based on the APIs provided by the navigation controller NavPathStack. For each Navigation component, a NavPathStack object must be created and passed to manage pages. NavPathStack mainly provides page navigation, page return, page replacement, page deletion, parameter acquisition, and route interception.
In API version 9, the Navigation component must be used together with the NavRouter component for page routing. Since API version 10, NavPathStack is recommended for page routing.
Key concepts related to routing:
NavPathStack and Navigation must map to each other and cannot be reused.
NavPathStack mainly controls NavDestination page redirection and deletion. It cannot directly operate the NavBar (navigation bar). If navigation to the NavBar page is required, you can only clear the navigation stack using the clear API.
Avoid relying on lifecycle event listeners to manage the navigation stack. Instead, you can query the navigation stack through NavPathStack.getPathStack.
When the application is in the background, calling stack operation APIs of NavPathStack will trigger a refresh upon the application's return to the foreground.
Declare the instantiation method for each NavDestination, for example, PageOneBuilder in the code. Executing this method creates a custom component of PageOne, which is a subpage of Navigation.
@Builder
export function PageOneBuilder(name: string, param: string) {
PageOne({ name: name, value: param });
}
@Component
export struct PageOne {
navPathStack: NavPathStack = new NavPathStack();
name: string = '';
@State value: string = '';
context = this.getUIContext().getHostContext();
build() {
NavDestination() {
// ...
}.title(`${this.name}`)
// ...
}
} The system provides system routing table and custom routing table. The former is used as an example. Register the instantiation method written in the subpage with its name (customized) in the routing table configuration file, which should be created in entry/src/main/resources/base/profile/router_map.json.
{
"routerMap": [
{
"name": "basicPageOne", // Unique identifier of the route page
"pageSourceFile": "src/main/ets/pages/PageOne.ets", // Path of the source code
"buildFunction": "PageOneBuilder" // Name of the instantiation method of the page
}
]
} After creating a routing table, register it with the project by configuring "routerMap": "$profile:router_map" in the module field of the project configuration file module.json5.
Since API version 12, the navigation controller can be inherited. You can customize attributes and methods in derived classes or override methods of the parent class. Objects of the derived class can be used as NavPathStack objects of the base class. For details about the sample code for overriding NavPathStack, see Defining a Derived Class of NavPathStack. The following describes the basic routing APIs provided by NavPathStack.
Page navigation
NavPathStack uses push-related APIs (such as pushPath, pushPathByName, pushDestination, and pushDestinationByName) to implement page navigation. Page navigation can be classified into the following types:
Normal navigation: Navigation is conducted by page name and allows for carrying parameters.
this.pageStack.pushPath({ name: 'pageOne', param: 'PageOne Param' }); this.pageStack.pushPathByName('pageTwo', 'PageTwo Param'); Navigation with a return callback: An onPop callback is added during navigation to obtain return information and process it upon page popping.
let DOMAIN = 0x0000;
this.pageInfo.pushPathByName('temp4-pageTwo', 'temp4-pageTwo Param', (popInfo) => {
hilog.info(DOMAIN, 'testTag', 'Pop page name is: ', popInfo.info.name, 'result: ',
JSON.stringify(popInfo.result));
// ...
}); Navigation with an error code: Upon failure, an asynchronous callback is triggered to provide the error code information.
const DOMAIN = 0x0000;
this.pageStack.pushDestination({
name: 'pageTwo', param: 'PageTwo Param'}).catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', '[pushDestination]failed', 'error code = ', error.code,
'error.message = ', error.message);
}).then(() => {
hilog.info(DOMAIN, 'testTag', '[pushDestination]success.');
}); const DOMAIN = 0x0000;
this.pageStack.pushDestinationByName('pageTwo', 'PageTwo Param').catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', '[pushDestinationByName]failed', 'error code = ', error.code,
'error.message = ', error.message);
}).then(() => {
hilog.info(DOMAIN, 'testTag', '[pushDestinationByName]success.');
}); Page return
NavPathStack implements the page return feature through pop-related APIs. Below shows the examples:
// Navigate back to the previous page. this.pathStack.pop();
// Navigate back to the previous pageOne page.
this.pathStack.popToName('temp4-pageOne'); // Navigate back to the page at index 0. this.pathStack.popToIndex(0);
// Navigate back to the root home page (clearing all pages in the stack). this.pageStack.clear();
Page replacement
NavPathStack provides replace-related APIs (such as replacePath, replacePathByName, and replaceDestination) to implement the page replacement functionality.
// Replace the top page of the stack with pageTwo.
this.pageStack.replacePath({ name: 'pageTwo', param: 'PageTwo Param' });
this.pageStack.replacePathByName('pageTwo', 'PageTwo Param'); const DOMAIN = 0x0000;
// Replacement with an error code: Upon failure, an asynchronous callback is triggered to provide the error code information.
this.pageStack.replaceDestination({ name: 'pageTwo', param: 'PageTwo Param' })
.catch((error: BusinessError) => {
hilog.error(DOMAIN, 'testTag', '[replaceDestination]failed', 'error code = ', error.code,
'error.message = ', error.message);
}).then(() => {
hilog.info(DOMAIN, 'testTag', '[replaceDestination]success.');
}) Page deletion
NavPathStack uses the remove-related APIs (such as removeByName, removeByIndexes, and removeByNavDestinationId) to delete a specific page from the navigation stack. Below shows the examples:
// Remove all pages whose name is pageTwo from the stack.
this.pageStack.removeByName('pageTwo'); // Remove the page with the specified index. this.pageStack.removeByIndexes([1]);
// Remove the page with the specified ID.
this.pageStack.removeByNavDestinationId('1'); Page moving
NavPathStack provides move-related APIs (such as moveToTop and moveIndexToTop) to move a specific page to the top of the navigation stack. Below shows the examples:
// Move the page named pageTwo to the top of the stack.
this.pageStack.moveToTop('pageTwo'); // Move the page at index 1 to the top of the stack. this.pageStack.moveIndexToTop(1);
The onReady callback is triggered when a NavDestination page is first created, allowing you to obtain parameters associated with that page.
@Component
struct Page01 {
pathStack: NavPathStack | undefined = undefined;
// ...
pageParam: string = '';
build() {
NavDestination() {
// ...
.title('Page01')
.onReady((context: NavDestinationContext) => {
this.pathStack = context.pathStack;
this.pageParam = context.pathInfo.param as string;
})
}
} To receive parameters passed when navigating back, you can use the onResult API of the NavDestination component.
class NavParam {
desc: string = 'navigation-param'
};
const DOMAIN = 0x0000;
// ...
@Component
export struct PageOne {
// ...
build() {
NavDestination() {
// ...
}
// ...
.onResult((param: Object) => {
if (param instanceof NavParam) {
console.info('TestTag', 'get NavParam, its desc: ' + (param as NavParam).desc);
return;
}
console.info('TestTag', 'param not instance of NavParam');;
})
}
} For other service scenarios, you can proactively call the getter APIs of NavPathStack (such as getAllPathName, getParamByIndex, getParamByName, and getIndexByName) to obtain parameters from specific pages.
// Obtain all page names in the stack.
this.pageStack.getAllPathName();
// Obtain the parameters of the page whose index is 1.
this.pageStack.getParamByIndex(1);
// Obtain the parameters of the PageOne page.
this.pageStack.getParamByName('PageOne');
// Obtain the index set of the PageOne page.
this.pageStack.getIndexByName('pageOne'); NavPathStack provides the setInterception API to set callbacks for page navigation interception of Navigation. This API requires passing in a NavigationInterception object, which contains multiple callback functions such as willShow and didShow. Different callback functions are invoked at different time. You can select an interception time based on the service requirements.
Take the willShow callback as an example. You can modify the navigation stack in the callback to implement route interception and redirection.
const DOMAIN = 0x0000;
this.pageStack.setInterception({
willShow: (from: NavDestinationContext | 'navBar', to: NavDestinationContext | 'navBar',
operation: NavigationOperation, animated: boolean) => {
if (typeof to === 'string') {
hilog.info(DOMAIN, 'testTag', 'target page is navigation home');
return;
}
// Redirect navigation intended for PageTwo to PageOne.
let target: NavDestinationContext = to as NavDestinationContext;
if (target.pathInfo.name === 'pageTwo') {
target.pathStack.pop();
target.pathStack.pushPathByName('pageOne', null);
}
}
}) The implementation procedure is as follows:
In the router_map.json file, define the global routing table. The navigation controller NavPathStack can push the corresponding page information onto the stack based on the name in the routing table.
{
"routerMap" : [
{
"name" : "WLAN",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "Bluetooth",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "Personal Hotspot",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "Connect & Share",
"pageSourceFile" : "src/main/ets/pages/PageTwo.ets",
"buildFunction" : "PageTwoBuilder"
},
{
"name" : "Projection",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "Print",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "VPN",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "Private DNS",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
},
{
"name" : "NFC",
"pageSourceFile" : "src/main/ets/pages/PageOne.ets",
"buildFunction" : "PageOneBuilder"
}
]
} Configure {"routerMap": "$profile:router_map"} in the project configuration file module.json5.
