app HTML界面传参: <a [routerLink]="['/']">主页</a> <a [routerLink]="['/product']" [queryParams]="{id: 1}">商品详细</a> <input type="button" value="商品目录" (click)="toProductDetail()"> <router-outlet></router-outlet>
product.ts界面接受参数
export class ProductComponent implements OnInit { public productId: number; constructor(private routerInfo: ActivatedRoute) { } ngOnInit(): void { this.productId = this.routerInfo.snapshot.queryParams["id"]; } }products HTML显示
<p>商品ID是{{productId}}</p>app-routing界面
const routes: Routes = [ {path: '', component:HomeComponent}, {path: 'product/:id', component:ProductComponent}, {path: '**', component:Code404Component}, ];app HTML传递参数
<a [routerLink]="['/']">主页</a> <a [routerLink]="['/product',2]">商品详细</a> <input type="button" value="商品目录" (click)="toProductDetail()"> <router-outlet></router-outlet>product TS显示信息,参数快照方式获取参数
ngOnInit(): void { this.productId = this.routerInfo.snapshot.params["id"]; }参数订阅方式获取参数(解决相同界面的跳转)
ngOnInit(): void { this.routerInfo.params.subscribe((params:Params) => this.productId = params["id"]); //this.productId = this.routerInfo.snapshot.params["id"]; }当组件从自身路由到自身时,选择用subscribe方式,否则使用snapshot方式节约资源。
重定向路由
{path: '', redirectTo: '/home',pathMatch:'full'},