DEV Community

Cover image for HarmonyOS Next Navigation and Routing Development Guide
liu yang
liu yang

Posted on • Edited on

HarmonyOS Next Navigation and Routing Development Guide

HarmonyOS Next Navigation and Routing Development Guide

I. Core Mechanism of Routing System

HarmonyOS Next is built on the ArkUI 5.0 routing engine and employs a layered management architecture. This architecture is designed to provide a robust and flexible routing system that supports various features essential for modern application development. The core components of this architecture include:

  • Routing Stack Management: Manages the navigation stack, allowing developers to control the flow of pages within the application.
  • Page Lifecycle Control: Ensures that pages go through a well-defined lifecycle, enabling proper initialization, rendering, and destruction.
  • Animation Transitions: Provides smooth and customizable animations for page transitions, enhancing the user experience.
  • Parameter Parsing: Facilitates the passing and parsing of parameters between pages, making it easier to share data.

Core Features

  • Multi-instance Modes: HarmonyOS Next supports two primary page instance modes:

    • Standard (default): Allows multiple instances of the same page, suitable for conventional multi-instance pages.
    • Single (singleton): Ensures that only one instance of a page exists globally, ideal for globally unique pages like login or settings pages.
  • Route Guards: These provide a mechanism to globally intercept navigation actions, enabling permission control and conditional navigation. This is particularly useful for implementing authentication and authorization flows.

  • Animation Choreography: The routing system supports over 15 preset transition animations and allows for custom animations, giving developers the flexibility to create unique and engaging user experiences.

II. Basic Page Navigation Methods

1. Standard Navigation (router.pushUrl)

The router.pushUrl method is used to navigate to a specified page. It supports passing parameters, which can be received on the target page.

// Navigate to a specified page
router.pushUrl({  
  url: 'pages/DetailPage',  
  params: { id: 123 }  
});  

// Receive parameters on the target page
@State params: Record<string, string> = router.getParams();
Enter fullscreen mode Exit fullscreen mode

Comparison of Routing Modes

Mode Memory Usage Applicable Scenario
Standard Higher Conventional multi-instance pages
Single Low Globally unique pages

2. Back Operation (router.back)

The router.back method allows navigation back to the previous page in the navigation stack. This is useful for implementing back navigation in your application.

// Navigate to a specified page
router.pushUrl({  
  url: 'pages/DetailPage',  
  params: { id: 123 }  
});  

// Receive parameters on the target page
@State params: Record<string, string> = router.getParams();

// Go back to the previous page
router.back();
Enter fullscreen mode Exit fullscreen mode

III. Parameter Passing in Routes

1. URL Parameter Passing

Parameters can be passed via the URL query string. The routing system automatically encodes and decodes these parameters.

// Send parameters (automatically encoded)
router.pushUrl({  
  url: `pages/DetailPage?id=${encodeURIComponent(123)}`  
});  

// Receive parameters (automatically decoded)
const id = decodeURIComponent(router.getParams()['id']);
Enter fullscreen mode Exit fullscreen mode

2. Object Parameter Passing

For more complex data, you can pass parameters as objects. These objects can be serialized to JSON strings and deserialized on the receiving page.

// Define parameter types
interface ProductParams {  
  id: number;  
  name: string;  
}  

// Send structured parameters
router.pushUrl({  
  url: 'pages/DetailPage',  
  params: {  
    product: JSON.stringify({ id: 1, name: 'Smartphone' })  
  }  
});  

// Receive and parse parameters
const product: ProductParams = JSON.parse(router.getParams()['product']);
Enter fullscreen mode Exit fullscreen mode

IV. Advanced Routing Features

1. Route Guards (Global Interception)

Route guards allow you to intercept navigation actions globally. This is useful for implementing permission control, such as redirecting users to a login page if they are not authenticated.

// Global before-hook
router.addBeforeHook((to, from, next) => {  
  if (to.url === 'pages/ProfilePage' && !isLogin) {  
    next({ url: 'pages/LoginPage' }); // Redirect to login page
  } else {  
    next(); // Proceed with navigation
  }  
});
Enter fullscreen mode Exit fullscreen mode

2. Dynamic Route Matching

Dynamic route matching allows you to define routes with dynamic segments. This is useful for creating pages that display content based on a parameter, such as a user profile page.

// Configure dynamic path
{  
  path: 'pages/UserPage/:userId',  
  name: 'UserPage'  
}  

// Pass parameters during navigation
router.pushUrl({  
  url: `pages/UserPage/${userId}`  
});  

// Get dynamic parameters on the target page
const userId = router.getParams()['userId'];
Enter fullscreen mode Exit fullscreen mode

3. Custom Transition Animations

You can customize the transition animations for page navigation. This allows you to create smooth and engaging user experiences.

router.pushUrl({  
  url: 'pages/DetailPage',  
  enterAnimation: {  
    duration: 500,  
    curve: Curve.EaseInOut,  
    type: RouteAnimation.SlideRight  
  }  
});
Enter fullscreen mode Exit fullscreen mode

V. Best Practices and Considerations

Type Definitions

Ensure that your parameter types are well-defined. This helps TypeScript understand the structure of your parameters and provides better type checking and autocompletion support.

Error Handling

Always include error handling for navigation actions. This ensures that your application can gracefully handle cases where navigation fails or parameters are missing.

router.pushUrl({  
  url: 'pages/DetailPage',  
  params: { id: 123 }  
}).catch((error) => {  
  console.error('Navigation failed:', error);  
});
Enter fullscreen mode Exit fullscreen mode

Performance Considerations

Be mindful of the performance implications of your routing choices. For example, using the Standard mode can lead to higher memory usage due to multiple instances of the same page. Use the Single mode for globally unique pages to save memory.

Testing

Thoroughly test your routing logic to ensure that all navigation paths work as expected. Pay special attention to edge cases, such as navigating to a page that does not exist or passing invalid parameters.

Top comments (0)