{ path: 'product/:id/:name', component: ProductComponent }
这里product.id和product.name都是在组件中定义的变量。
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router';
@Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { id: string; name: string;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void { this.id = this.route.snapshot.params['id']; this.name = this.route.snapshot.params['name']; } }
在组件中注入ActivatedRoute服务,并在ngOnInit生命周期中使用snapshot属性获取路由参数的值。