Difference between getting url query string with $ routeParams vs $ location. $$ search

If I have a specific route parameter that is always passed as a query string, is there a difference between retrieving the parameter using the angular service $routeParams

and using its service $location.$$search

? If so, is it preferable to the other?


Url: //localhost:80/app/profile?id=42

$routeParams

:

app.controller('ProfileController', ['$routeParams', function($routeParams) {
  console.log($routeParams.id);
}]);

      


Approach $location

:

app.controller('ProfileController', ['$location', function($location) {
  console.log($location.$$search.id);
}]);

      


I am already injecting $location

as a dependency in the controller that should execute the behavior detailed in the question. In addition, the controller module does not yet have a dependency on ngRoute

.

+3


source to share


2 answers


If your route is of type:

when('page/:id')

      

then searching for $ location will not give you an id in the search results. But $ routesParams does.



But in the case of ex query parameters:

when('page?key=value&key2=value2')

      

In this case, you can navigate to either $ location.search or $ routeParams.

+5


source


It also seems that the $ location path is faster in some ways (which is natural, since $ routeParams uses $ location to get its values).

To explain: My site has a mode that is only for tablet kiosk use, whereas the typical use case is for clients using their own devices. To differentiate, I start kiosk tablets by going to https: //mysite.url/? Kiosk , which triggers this action (which is executed on boot):

if($routeParams.kiosk){
    $cookieStore.put("kiosk", true);
}

      

This has now tended to crash as $ routeParams did not have time to initialize, which is close to loading. Go to



if($location.search().kiosk){
    $cookieStore.put("kiosk", true);
}

      

mitigated this problem.

(My site is currently stuck on Angular 1.2.19 and was not compiled by people who had all the modern best practices. My example may or may not be relevant for modern projects coded by competent developers;))

+1


source







All Articles