AngularJS - 静默更改$ location - 删除查询字符串

时间:2014-02-16 18:32:24

标签: angularjs

有没有办法使用angular?

以静默方式更改网址栏中的路径

用户点击发送到的电子邮件的链接:

/verificationExecuted?verificationCode=xxxxxx

当页面加载时我想读取verificationCode然后清除它:

 if($location.path() == '/verificationExecuted'){
     this.registrationCode = this.$location.search()["verificationCode"];
     this.$location.search("verificationCode", null); //Uncomment but make this silent!

     if(registrationCode != null) {
         ....
     }
     else $location.path("/404");      
 }

当我清除它时会发生什么?路由的剩余部分(“/ verifyExecuted”)仍然存在,但路由重新触发,所以它再次出现,没有verifyCode,直接进入404。

我想删除代码而不做其他事情。

4 个答案:

答案 0 :(得分:27)

您始终可以将路线上的reloadOnSearch选项设为false.

如果只查询字符串发生更改,它将阻止路由重新加载:

$routeProvider.when("/path/to/my/route",{
   controller: 'MyController',
   templateUrl: '/path/to/template.html',
   //Secret Sauce
   reloadOnSearch: false
});

答案 1 :(得分:5)

试试这个

$location.url($location.path())

有关$ location

的详细信息,请参阅documentation

答案 2 :(得分:0)

我对我的一个项目有类似的要求。

我在这种情况下所做的是使用服务。

app.factory('queryData', function () {
    var data;

    return {
        get: function () {
            return data;
        },
        set: function (newData) {
            data = newData
        }
    };
});

此服务随后在我的控制器中用作:

app.controller('TestCtrl', ['$scope', '$location', 'queryData',
    function ($scope, $location, queryData) {
        var queryParam = $location.search()['myParam'];
        if (queryParam) {
            //Store it
            queryData.set(queryParam);
            //Reload same page without query argument
            $location.path('/same/path/without/argument');
        } else {
            //Use the service
            queryParam = queryData.get();
            if (queryParam) {
                //Reset it so that the next cycle works correctly
                queryData.set();
            }
            else {
                //404 - nobody seems to have the query
                $location.path('/404');
            }
        }
    }
]);

答案 3 :(得分:0)

我通过添加一种更改路径并取消事件的方法解决了这个问题。

 public updateSearch(){

            var un = this.$rootScope.$on('$routeChangeStart', (e)=> {
                
                e.preventDefault();
                
                un();
                
            });
            
            this.$location.search('new',search.searchFilter);
            
            if (!keep_previous_path_in_history) this.$location.replace();
            
}