1. How to pass parameters when routing
1. Pass data in query parameters
// page <a routerLink="/product" [queryParams]="{id:1}" > Product Details </a> _ _ _
// ts gets parameters export class ProductComponent implements OnInit { private productId: number; constructor(private routeInfo: ActivatedRoute) { } by OnInit () { this.productId = this.routeInfo.snapshot.queryParams['id']; } }
The corresponding background acquisition is: ActivedRoute.queryParams[id]
2. Pass data in the routing path
// page <a [routerLink]="['product', 1]" > Product Details </a> _
// Background page, modify the routing definition first, const routes in app-routing.modules.ts : Routes = [ {path: 'product/:id', component: ProductComponent}, {path: '**', component: HomeComponent}, ]; this.productId = this.routeInfo.snapshot.params['id'];
When the route is defined, it is defined as: product/:id, where ":id" represents the parameter
3. Pass data in routing configuration
//Page < input type = "button" value = "Product Details" (click) = 'toProductDetails()' >
Page jump:
constructor( private router: Router, // The Router module needs to be injected here ){} toProductDetails(){ // This is the click jump event bound in html this .router.navigate(['product-detail' ], { queryParams: { productId: '1', title: 'moon' } }); }
Receive parameters:
constructor( private activatedRoute: ActivatedRoute, // The ActivatedRoute module needs to be injected here ) { activatedRoute.queryParams.subscribe(queryParams => { let productId = queryParams.productId; let title = queryParams.title; }); }
2. Ways to receive routing parameters in the background
1. There are two types of snapshot and subscribe. The difference is that when the routing address remains unchanged, if the parameters sent change, the parameters received by the latter will also change, and the former will remain unchanged.
3. Routing redirection
When visiting a specific address, it will be redirected to another specified address
1 //When defining the route 2 {path: '', redirectTo: '/home', pathMatch: 'full' }, 3 {path: 'home', component : HomeComponent},
refer to:
Angular routing parameter passing
The most nice way to pass parameters and get parameters in angular4.0