MST

星途 面试题库

面试题:Angular路由如何处理复杂的嵌套路由及参数传递实现单页应用深度导航

假设一个电商单页应用,产品详情页有多层嵌套路由,如产品规格、评论等子路由,且需要传递多种参数(如产品ID、用户ID等)。请阐述如何在Angular路由中实现这种复杂的嵌套路由及参数传递,确保导航的准确性和数据的一致性。
38.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 配置路由模块
    • app - routing.module.ts中,首先定义产品详情页的主路由,例如:
    const routes: Routes = [
        {
            path: 'product/:productId',
            component: ProductDetailComponent,
            children: [
                {
                    path:'specification',
                    component: ProductSpecificationComponent
                },
                {
                    path:'review',
                    component: ProductReviewComponent
                }
            ]
        }
    ];
    
    • 这里product/:productId定义了产品详情页的路由,并通过:productId捕获产品ID参数。children数组定义了嵌套路由,分别是specificationreview
  2. 传递其他参数
    • 如果还需要传递用户ID等其他参数,可以通过queryParams。在导航到产品详情页时,可以这样传递参数:
    this.router.navigate(['/product', productId], { queryParams: { userId: this.userId } });
    
    • 在目标组件(如ProductDetailComponent及其子组件)中获取参数:
    import { ActivatedRoute } from '@angular/router';
    constructor(private route: ActivatedRoute) {}
    ngOnInit() {
        const productId = this.route.snapshot.paramMap.get('productId');
        const userId = this.route.snapshot.queryParamMap.get('userId');
    }
    
  3. 确保导航准确性和数据一致性
    • 导航准确性
      • 使用routerLink指令在模板中创建链接,确保路径拼写正确。例如:
      <a [routerLink]="['/product', productId,'specification']">产品规格</a>
      <a [routerLink]="['/product', productId,'review']">产品评论</a>
      
      • 对于编程式导航,使用this.router.navigate时,确保传递的参数和路径准确无误。
    • 数据一致性
      • 可以使用服务(Service)来共享数据。例如,创建一个ProductDataService,在产品详情页组件及其子组件中注入该服务。
      @Injectable({
          providedIn: 'root'
      })
      export class ProductDataService {
          private product: Product;
          setProduct(product: Product) {
              this.product = product;
          }
          getProduct() {
              return this.product;
          }
      }
      
      • ProductDetailComponent中获取产品数据后,调用setProduct方法存储数据,子组件(如ProductSpecificationComponentProductReviewComponent)通过注入ProductDataService并调用getProduct方法获取相同的数据,保证数据一致性。