【问题标题】:How to retrieve query params from encoded url in angular2?如何从angular2中的编码url中检索查询参数?
【发布时间】:2018-05-07 08:31:34
【问题描述】:

如果 URL 如下所示,我可以获取查询参数:

http://localhost:4200/member/0?members=1&facility=1&field=name&criteria=contains&string=black

当浏览器对上述网址中的$=? 进行编码时,我无法检索查询参数,

编码后的 URL 如下所示:

http://localhost:4200/ccm/member/0/search/submitted%3Fmembers%3D1%26facility%3D1%26field%3Dname%26criteria%3Dcontains%26string%3Dblack

下面是一段代码,我试图检索查询参数(在 URL 未编码时工作正常,但在浏览器对 URL 编码时失败)。

this._activatedRoute.snapshot.queryParams;

this._activatedRoute.queryParams.subscribe(value=> {
   console.log('here');
   console.log(value);
});

我使用的是Angular版本2.3.1,路由器版本是3.3.1

【问题讨论】:

  • constructor( private route: ActivatedRoute, private router: Router) {} ngOnInit() { this.sub = this.route .queryParams .subscribe(params => { // Defaults to 0 if no query param provided. this.page = +params['page'] || 0; }); }
  • @KishanOza,它不起作用。获取默认值 0

标签: angular angular2-routing


【解决方案1】:

这是您如何从 URL 获取参数的示例。

网址是这样的:

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

那么代码会是这样的:

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: "popular"}

        this.order = params.order;
        console.log(this.order); // popular
      });
  }
}

【讨论】:

  • 过滤器中的params.order 是什么?它是从 URL 中检索所有查询参数还是只检索一个??
  • 如果你有这样的网址http://localhost:4200/products?order=popular 理解??
  • 是的,但是没有用。就我而言,我有member。所以当我使用filter(params=>params.member) 时,IDE 会显示facilityparams 上不存在。如果我删除 filter 以获取所有查询参数,则值为 null
  • 你可以使用这个函数来解码url decodeURIComponent(params)
  • 我们可以,但前提是参数不为空。我自己并没有获得价值。
猜你喜欢
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 2022-11-27
  • 2011-09-06
  • 2011-07-16
  • 2018-12-23
  • 1970-01-01
相关资源
最近更新 更多