Angular 入门到精通 #04 - Add Navigation

104 阅读1分钟

本章基于之前的应用程序,添加一个产品详情组件,并通过配置的URL来访问该组件。

Associate a URL path with a component

下面演示如何定义一个新的路由来显示产品详情页面。

  1. 运行下面的命令来创建一个新的组件product-details.

    ng generate component product-details
    
  2. 在文件app-routing.module.ts中,修改代码如下:

    const routes: Routes = [
      { path: '', component: ProductListComponent },
      { path: 'products/:productId', component: ProductDetailsComponent }
    ];
    
  3. 修改文件product-list.component.html,代码如下。routerLink是Angular Router的属性,指定需要导航的路由。

    <h3>
        <a 
            title="{{product.name}}"
            [routerLink]="['/products', product.id]"
        >{{product.name}}</a>
    </h3>
    
  4. 修改文件app.component.html,用下面的代码替换<app-product-list></app-product-list>。这是一个路由器的占位符,会根据不同的路由来渲染对应的组件。

    <router-outlet></router-outlet>
    
  5. 最终实现的效果如下:

    Product Details

View product details

接下来,我们使用组件product-details来展现产品详情。

  1. 在文件product-details.component.ts中,定义product属性,并在构造函数中注入 ActivatedRoute,代码如下:

    export class ProductDetailsComponent {
      product: Product | undefined;
    
      constructor(
        private route: ActivatedRoute
      ){}
    }
    
  2. ngOnInit方法中,获取数据productId,并从products集合中获得对应的数据。我们使用route.snapshot 来获取路由里包含的数据。

    export class ProductDetailsComponent {
      product: Product | undefined;
    
      constructor(
        private route: ActivatedRoute,
        private readonly productsService: ProductsService
      ){}
    
      ngOnInit(): void {
        const routeParams = this.route.snapshot.paramMap;
        const productId = Number(routeParams.get('productId'));
    
        this.product = this.productsService.getProductList().find(product => product.id === productId);
      }
    }
    
  3. 修改文件product-details.component.html,显示产品的详细信息。

    <div class="productDetails">
        <h2>Product Details</h2>
    
        <div *ngIf="product">
            <h3>{{product.name}}</h3>
            <h4>{{product.price | currency}}</h4>
            <p>{{product.description}}</p>
        </div>
    </div>
    
  4. 最早的实现效果如下。

    Product Details