fix: improve type safety and error handling in arkts-development

- Replace Record<string, Object> with specific interface types for router params
- Add error handling catch block to list-page-template.ets
- Add clarification note for router.back() with params
- Improve type safety following ArkTS best practices
This commit is contained in:
cheliangzhao
2026-02-10 20:52:17 +08:00
parent 81b3c82d16
commit 9d902b1074
3 changed files with 45 additions and 31 deletions

View File

@@ -96,7 +96,11 @@ router.replaceUrl({ url: 'pages/New' });
router.back(); router.back();
// Get params // Get params
const params = router.getParams() as Record<string, Object>; interface RouteParams {
id: number;
title?: string;
}
const params = router.getParams() as RouteParams;
``` ```
## Network Request ## Network Request

View File

@@ -20,18 +20,21 @@ struct {{PageName}} {
this.loadItems(); this.loadItems();
} }
async loadItems(): Promise<void> { async loadItems(): Promise<void> {
this.isLoading = true; this.isLoading = true;
try { try {
// TODO: Fetch items from API // TODO: Fetch items from API
this.items = [ this.items = [
{ id: '1', title: 'Item 1', description: 'Description 1' }, { id: '1', title: 'Item 1', description: 'Description 1' },
{ id: '2', title: 'Item 2', description: 'Description 2' }, { id: '2', title: 'Item 2', description: 'Description 2' },
]; ];
} finally { } catch (error) {
this.isLoading = false; console.error('Failed to load items:', error);
} // TODO: Show error message to user
} } finally {
this.isLoading = false;
}
}
async refreshItems(): Promise<void> { async refreshItems(): Promise<void> {
this.isRefreshing = true; this.isRefreshing = true;

View File

@@ -65,24 +65,31 @@ router.back({
url: 'pages/HomePage' url: 'pages/HomePage'
}); });
// Back with result // Back with result
router.back({ router.back({
url: 'pages/HomePage', url: 'pages/HomePage',
params: { result: 'success' } params: { result: 'success' }
}); });
``` // Note: Previous page receives params via router.getParams()
```
### Get Parameters
### Get Parameters
```typescript
// In target page ```typescript
aboutToAppear(): void { // Define expected params interface
const params = router.getParams() as Record<string, Object>; interface PageParams {
if (params) { id: number;
const id = params['id'] as number; title?: string;
const title = params['title'] as string; }
}
} // In target page
aboutToAppear(): void {
const params = router.getParams() as PageParams;
if (params) {
const id = params.id;
const title = params.title;
}
}
``` ```
### Get Router State ### Get Router State