如何使用其他函数传递查询参数

how to pass the query parameter with the othwerwise function

给出以下 javascript:

$stateProvider
  .state('search', {
    url: '/search?query',
})   
;

$urlRouterProvider.otherwise("search");

当我访问页面时

base_url?query=x

我被重定向到

base_url/search

但是查询参数丢失了。

有没有办法用otherwise函数传递查询参数?

a working plunker

UI-路由器在这里有本地解决方案。

The otherwise does not have to be the "url" string, it could be a function.

在此问答中检查它的运行情况:

How not to change url when show 404 error page with ui-router

代码可能是这样的:

$urlRouterProvider.otherwise(function($injector, $location){
    var state = $injector.get('$state');
    state.go("search", $location.search()); // here we get { query: ... }
    return $location.path();
});

$location.search() 会给我们 params 对象,它可以是这样的:{ query: ... }。我们接受它并使用此参数重定向到状态搜索...

检查一下here

你根本不需要拿注射器和$state.go,根本不需要。 otherwise 方法的参数可以是 URL 路径,其中可以 包含参数 .

因此,在您的特定情况下,以下代码可以将您引导至 base_url/search?query=x

$urlRouterProvider.otherwise("/search?query=x");

或者,参数可以是 return 一个 URL 路径的函数。如果您不确定它可能有哪些 URL 参数,您只需要从 $location 获取参数,然后格式化为 URL-like 字符串和 return 它。

$urlRouterProvider.otherwise(function($injector, $location) {
    var params = $location.search()

    // format params to 'p1=v1&p2=v2' style
    var formatted = Object.keys(params).map(function(key) {
        return key + '=' + params[key]
    }).join('&')

    return '/search?' + formatted
});