Passing Optional Parameters

Query parameters allow you to pass optional parameters to a route such as pagination information.

For example, on a route with a paginated list, the URL might look like the following to indicate that we've loaded the second page:

localhost:3000/product-list?page=2

The key difference between query parameters and route parameters is that route parameters are essential to determining route, whereas query parameters are optional.

Passing Query Parameters

Use the [queryParams] directive along with [routerLink] to pass query parameters. For example:

  1. <a [routerLink]="['product-list']" [queryParams]="{ page: 99 }">Go to Page 99</a>

Alternatively, we can navigate programmatically using the Router service:

  1. goToPage(pageNum) {
  2. this.router.navigate(['/product-list'], { queryParams: { page: pageNum } });
  3. }

Reading Query Parameters

Similar to reading route parameters, the Router service returns an Observable we can subscribe to to read the query parameters:

  1. import { Component } from '@angular/core';
  2. import { ActivatedRoute, Router } from '@angular/router';
  3. @Component({
  4. selector: 'product-list',
  5. template: `<!-- Show product list -->`
  6. })
  7. export default class ProductList {
  8. constructor(
  9. private route: ActivatedRoute,
  10. private router: Router) {}
  11. ngOnInit() {
  12. this.sub = this.route
  13. .queryParams
  14. .subscribe(params => {
  15. // Defaults to 0 if no query param provided.
  16. this.page = +params['page'] || 0;
  17. });
  18. }
  19. ngOnDestroy() {
  20. this.sub.unsubscribe();
  21. }
  22. nextPage() {
  23. this.router.navigate(['product-list'], { queryParams: { page: this.page + 1 } });
  24. }
  25. }

View Example

See Official Documentation on Query Parameters

原文: https://angular-2-training-book.rangle.io/handout/routing/query_params.html