How to pass query parameter using otwerwise function

Given the following javascript:

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

When I access the page

 base_url?query=x 

I'm redirecting to

base_url / search

but the request parameter is lost.

Is there a way to pass the request parameter otherwise?

+6
source share
2 answers

There is a working plunker

UI-Router has its own solution.

otherwise doesn't have to be the string "url", it could be a function.

Check it out in action in this Q and A:

How to not change the url when showing 404 error page using ui-router

The code may be like this:

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

$location.search() will provide us with a params object, which may be the following: { query: ... } . We take it and redirect it to search by request using these parameters ...

Check here

+8
source

You do not need to grab the injector and $ state.go, not at all. The argument to the otherwise method may be a URL that may contain parameters in it .

So, in your particular case, the following code can lead you to base_url / search? query = x

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

Alternatively, the argument may be a function that returns a URL. If you donโ€™t know what URL parameters you might have, you just need to get the parameters from $location and then format them in a string similar to the URL and return it.

 $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 }); 
0
source

Source: https://habr.com/ru/post/986234/


All Articles