获取URL查询字符串与$ routeParams与$ location.$$搜索之间的区别

har*_*z89 3 angularjs ngroute

如果我有一个始终作为查询字符串传递的特定路由参数,那么使用angular的$routeParams服务检索param 和使用其$location.$$search服务之间是否存在差异?如果是这样,一个比另一个好吗?


网址: //localhost:80/app/profile?id=42

$routeParams 做法:

app.controller('ProfileController', ['$routeParams', function($routeParams) {
  console.log($routeParams.id);
}]);
Run Code Online (Sandbox Code Playgroud)


$location 做法:

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


我已经$location在控制器中作为依赖注入,需要执行问题中详述的行为.此外,控制器的模块还没有依赖ngRoute.

Cha*_*dla 5

如果您的路线是类型:

when('page/:id')
Run Code Online (Sandbox Code Playgroud)

然后使用$ location搜索将不会在搜索结果中提供ID.但$ routesParams确实如此.

但在查询参数ex的情况下:

when('page?key=value&key2=value2')
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以使用$ location.search或$ routeParams中的任何一个.