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

╄→尐↘猪︶ㄣ 提交于 2019-12-10 17:47:09

问题


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 ;-) )



来源:https://stackoverflow.com/questions/26807271/difference-between-getting-url-query-string-with-routeparams-vs-location-sea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!