在 Angular 中获取任何 URL 参数

Get any URL parameter in Angular

在 PHP 中你得到所有 URL 参数

print_r($_GET);

在JavaScript中是这样的

window.onload = function() {
  GetURLParameter();
};

function GetURLParameter()
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        var oldValue = document.getElementById("result").value;
        var newValue = oldValue + '\n' + sParameterName[0] + ': ' + sParameterName[1];
        document.getElementById("result").value = newValue;
    }
}​

然后在 Angular?

我看到的例子都是查询某个参数。您必须事先知道该参数。例如

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'url-call';
  paramList: string[] = [];
  param1: string;

  constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    console.log(this.activatedRoute.snapshot.queryParamMap.get("param1"));
    this.activatedRoute.queryParamMap.subscribe(queryParams => {
      console.log(queryParams.get("param1"));
    })

  }
}

如何在不知道参数名称的情况下打印出 all/any 参数?

另外queryParamMapqueryParams有什么区别?

如果您想将所有参数作为一个对象获取,您可以这样做

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

如果你的URL是这样的

http://localhost:4200/products?order=popular&filter=new

this.orderObj 将包含

{
  "0": "order",
  "1": "filter",
  "params": {
    "order": "popular",
    "filter": "new"
  }
}

更新:

queryParamMap:可观察: 一个 Observable,其中包含可用于所有路由的查询参数的映射。该地图支持从查询参数中检索单个值和多个值。

queryParams:可观察 所有路由共享的查询参数的可观察值。

请检查这个link