发布于 1年前

在Angular Router中使用查询参数QueryParameter

会涉及到的api有:Angular RouterRouterLinkActivatedRoute

在Router.navigate中使用查询参数

单参数

如果使用 Router.navigate 路由,navigate提供了queryParams 用作查询参数传递。

toProducts() {
  this.router.navigate(
    ['/products'],
    { queryParams: { order: 'latest' } }
  );
}

示例中,路由到产品页,并且使用latest来做排序。其中order=latest就是查询参数。此路由的结果是:

http://localhost:4200/products?order=latest

多参数

这里添加一个分类参数category=computer作为过滤,如下:

toProducts() {
  this.router.navigate(
    ['/products'],
    { queryParams: { order: 'latest', 'category': 'computer' } }
  );
}

得到的url结果是:

http://localhost:4200/products?order=latest&category=computer

使用 queryParamsHandling 保留或合并查询参数

默认情况下,任何后续的跳转会丢失查询参数。为了防止这种情况,可以将 queryParamsHandling 设置为“preserve”或“merge”。

保留参数preserve

假设目前的链接是:

http://localhost:4200/products?order=latest

现在需要跳转到用户列表,并且希望保留order=latest参数,即跳转后的链接为:

http://localhost:4200/users?order=latest

实现此需求的办法就是使用queryParamsHandling,设置为“preserve”:

toUsers() {
  this.router.navigate(
    ['/users'],
    { queryParamsHandling: 'preserve' }
  );
}

合并参数merge

如果users链接还有自己的参数,如分页pageNum=1,并且想保留order=latest,得到的链接是:

http://localhost:4200/users?order=latest&pageNum=1

实现此需求的办法就是使用queryParamsHandling,设置为“merge”:

toUsers() {
  this.router.navigate(
    ['/users'],
    {
      queryParams: { pageNum: '1' },
      queryParamsHandling: 'merge' }
    );
}

在RouterLink使用查询参数

上面的示例,如果是使用RouterLink指令,产品列表实现如下:

<a
  [routerLink]="['/products']"
  [queryParams]="{ order: 'latest'}"
>
  Products
</a>

跳转到用户列表,保留/products的参数order=latest,并且添加自己的参数pageNum:

<a
   [routerLink]="['/users']"
   [queryParams]="{ pageNum: '1' }"
   queryParamsHandling="merge"
>
  Users
</a>

获取查询参数的值

上面说明了在路由中传递参数,这里说明如何获取参数。

使用queryParams

上面示例中的产品列表:

http://localhost:4200/products?order=latest

使用queryParams获取order参数的值:

import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/filter';

@Component({ ... })
export class ProductComponent implements OnInit {
  order: string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.queryParams
      .filter(params => params.order)
      .subscribe(params => {
        console.log(params); // { order: "latest" }

        this.order = params.order;

        console.log(this.order); // latest
      }
    );
  }
}

在注释里输出{ order: "latest" }latest

使用queryParamMap

queryParamMap想返回一个带有 paramMap 对象的 Observable。

链接如下:

http://localhost:4200/users?order=latest&pageNum=1

访问查询参数如下:

this.route.queryParamMap
  .subscribe((params) => {
    this.orderObj = { ...params.keys, ...params };
  }
);

这里使用对象扩展运算符,得到的对象:

{
  "0": "order",
  "1": "pageNum",
  "params": {
    "order": "latest",
    "filter": "1"
  }
}
©2020 edoou.com   京ICP备16001874号-3