Angular 5基于数据库分类列表创建路由:特殊字符处理咨询
Great question! When dealing with category names that have HTML entities like & (the encoded version of &) and spaces, you need to convert these into URL-safe path segments (called slugs) while still being able to map back to the original category name. Here's a step-by-step solution tailored for Angular 5:
1. Create a Slug Utility Function
First, build a helper function to transform your category names into clean, URL-friendly slugs. This handles decoding HTML entities, replacing special characters, and normalizing spaces:
// src/app/utils/slugify.ts export function slugifyCategory(categoryName: string): string { // Step 1: Decode HTML entities like & to & const decodedName = categoryName.replace(/&/g, '&'); // Step 2: Convert to lowercase, replace & with "and", clean up non-alphanumeric chars return decodedName .toLowerCase() .replace(/&/g, 'and') // Replace & with readable "and" instead of encoding .replace(/[^a-z0-9]+/g, '-') // Replace spaces/special chars with dashes .replace(/^-+|-+$/g, ''); // Remove leading/trailing dashes }
For example:
Apparel & Clothing→apparel-and-clothingBus Tickets→bus-ticketsKids & Children→kids-and-children
2. Generate Routes Dynamically
Use your category list and the slug function to build your Angular routes automatically. Store the original category name in the route's data property so your component can access it later:
// src/app/app-routing.module.ts import { Routes, RouterModule } from '@angular/router'; import { CategoryComponent } from './category/category.component'; import { slugifyCategory } from './utils/slugify'; // Your category list from the database const categories = [ "Travel", "Apparel & Clothing", "Footwear", "Kids & Children", "Grocery", "Food & Beverage", "Innerwear & Swimwear", "Hotels", "Bus Tickets", "Mobiles & Tablets", "Personalized Gifts", "Jewellery & Coins", "Car & Taxi Rental", "Pharmacy", "Watches", "Bags & Wallets", "Gifts & Flowers", "Accessories", "Games", "Health", "Beauty & Personal Care", "Electronics" ]; // Generate route config for each category const categoryRoutes = categories.map(category => ({ path: slugifyCategory(category), component: CategoryComponent, data: { originalCategory: category } // Store original name for component use })); // Main routes array const routes: Routes = [ // Your other routes here... ...categoryRoutes // Add dynamic category routes ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
3. Access the Original Category in Your Component
In your CategoryComponent, use ActivatedRoute to fetch the original category name from the route's data property:
// src/app/category/category.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-category', templateUrl: './category.component.html', styleUrls: ['./category.component.css'] }) export class CategoryComponent implements OnInit { currentCategory: string; constructor(private route: ActivatedRoute) { } ngOnInit(): void { // Get original category name from route data this.route.data.subscribe(data => { this.currentCategory = data.originalCategory; // Use this value to fetch category-specific data, render titles, etc. }); } }
4. Navigate to Category Routes
When linking to a category route (e.g., from a navigation menu), use the slug function to generate the correct path:
<!-- In a template --> <a [routerLink]="[slugifyCategory(category)]">{{ category }}</a>
Or in TypeScript:
// In a component/service import { Router } from '@angular/router'; import { slugifyCategory } from './utils/slugify'; constructor(private router: Router) { } navigateToCategory(category: string): void { this.router.navigate([slugifyCategory(category)]); }
Alternative: Use Route Parameters
If you prefer a more flexible approach (e.g., if categories might change dynamically), use a single route with a slug parameter and map slugs back to categories:
// Route config const routes: Routes = [ { path: 'category/:slug', component: CategoryComponent } ]; // In CategoryComponent ngOnInit(): void { this.route.paramMap.subscribe(params => { const slug = params.get('slug'); // Find the original category by matching slugs this.currentCategory = categories.find(cat => slugifyCategory(cat) === slug); }); }
This works well if you fetch categories dynamically from an API instead of hardcoding them.
内容的提问来源于stack exchange,提问作者user6579211

