-->

Difference between getting URL query string with $

2019-07-02 05:58发布

问题:

If I have a specific route parameter that is always being passed as a query string, is there a difference between retrieving the param using angular's $routeParams service and using its $location.$$search service? If so, is one preferable to the other?


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

$routeParams approach:

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


$location approach:

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


I am already injecting $location as a dependency in the controller that needs to perform the behavior detailed in the question. Additionally, the controller's module does not yet have a dependency on ngRoute.

回答1:

If your route is of type:

when('page/:id')

then using $location search won't give you the ID in the search result. But $routesParams does.

But in case of query params ex:

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

In this case, you can go for any of $location.search or $routeParams.



回答2:

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

To explain: My site has a mode that's only meant to be used by kiosk tablets, whereas the normal use case is customers using their own devices. To differentiate, I initiate kiosk tablets by going to https://mysite.url/?kiosk, which triggers this (which runs on load):

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

Now, this tended to fail, since $routeParams hadn't had time to become initialized that close to load. Switching to

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

mitigated that issue.

(My site is currently stuck on Angular 1.2.19, and was not put together by people who had all current best practices in mind. My example may or may not be relevant to modern projects coded by competent developers ;-) )