【问题标题】:How to deal with query strings before and after the hash in Angular如何在Angular中处理哈希之前和之后的查询字符串
【发布时间】:2016-09-01 15:52:11
【问题描述】:

我正在使用 Angular v1.4.2

我目前正在处理一个如下所示的查询字符串:

http://localhost/myProject/apply/?A=100&B=ABC&C=Test#/step1?D=3&E=X1&F=1

所以这意味着A、B和C在哈希之前声明 D、E、F在散列后声明

我无法更改此 URL,因为它是由外部 API 生成的,而且 URL 需要这样也是有原因的。

我一直在尝试寻找读取所有参数的方法。到目前为止我尝试过的事情:

$location.search(); 仅返回 {D, E, F}

理想情况下$location.search(); 应该返回{A,B, C, D, E, F}

其中一个解决方案建议更改位置提供程序设置。我的是这些:

function $LocationProvider() {
  var hashPrefix = '',
      html5Mode = {
        enabled: false,
        requireBase: true,
        rewriteLinks: true
      };

将这些设置更改为:

function $LocationProvider() {
  var hashPrefix = '',
      html5Mode = {
        enabled: true,
        requireBase: false,
        rewriteLinks: false
      };

没有解决任何问题,无论如何,对于这么大的项目,我不想弄乱这些设置。

有没有办法读取所有查询字符串参数?

【问题讨论】:

  • 看不到链接的外观示例
  • 使用你知道的,老派 BOM:location.search,没有$,没有()。浏览器中的普通 ole JavaScript。
  • Rani,我不希望链接看起来有任何不同。我想从控制器读取查询字符串参数。链接可以保持原样

标签: angularjs query-string


【解决方案1】:

我最终得到了这个。如果有更好的方法,我想知道

创建了一个读取左侧所有参数的工厂。 此时无法读取右边的参数。

   export class QueryStringFactory {

        static $inject = ["$window", "$location"];

        private window: ng.IWindowService;
        private location: angular.ILocationService;

        constructor(public $window: ng.IWindowService, public $location: angular.ILocationService) {
            this.window = $window;
            this.location = $location;
        }

        searchLeft() {
            var left = window.location.search
                .split(/[&||?]/)
                .filter((x) => { return x.indexOf("=") > -1; })
                .map((x) => { return x.split(/=/); })
                .map((x) => {
                    x[1] = x[1].replace(/\+/g, " ");
                    return x;
                })
                .reduce((acc, current) => {
                    acc[current[0]] = current[1];
                    return acc;
                }, {});
            return left;
        }

        static factory() {
            var instance = ($window: ng.IWindowService, $location: angular.ILocationService) =>
                new QueryStringFactory($window, $location);
            return instance;
        }
    }

注册工厂:

angular.factory("QueryStringFactory", Utils.QueryStringFactory.factory());

并像这样在控制器中使用它:

    constructor(public $window: angular.IWindowService | any,
        public $location: angular.ILocationService, public queryString: Utils.QueryStringFactory) {

        var qsParamsRight = $location.search();
        var qsParamsLeft = queryString.searchLeft();
        var qsAllParams = $.extend(true, {}, qsParamsLeft, qsParamsRight);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多