【问题标题】:Get any URL parameter in Angular获取 Angular 中的任何 URL 参数
【发布时间】:2020-01-12 10:29:20
【问题描述】:

在 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"));
    })

  }
}

如何在不知道参数名称的情况下打印出所有/任何参数?

另外queryParamMapqueryParams有什么区别?

【问题讨论】:

    标签: angular angular7 url-parameters


    【解决方案1】:

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

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

    如果你的网址是这样的

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

    this.orderObj 将包含

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

    更新:

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

    同时

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

    请查看link

    【讨论】:

    • 如何打印出orderObj?这行代码使{...params.keys, ...params} 做什么?
    • TypeScript 中有一个叫做 Object Rest and Spread 的东西。请参考alligator.io/typescript/object-rest-spread 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2018-05-29
    • 2014-01-06
    • 2018-05-07
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多