我是第一次尝试 angular.js。 我的休息服务配置如下:
get('/api/users') //returns a JSON Array with all the users
get('/api/users/:id') //returns a JSON object with the requested ID
我的 Angular Controller 设置如下:
UserCtrl.factory('User', function($resource) {
return $resource('/api/users/:id', { id: '@id' }, { update: { method: 'PUT' } });
});
var EditCtrl = function($scope, $location, $routeParams, User){
var id = $routeParams._id;
$scope.user = User.get({id: id});
};
我的问题是当我运行时
User.get({id: id})
请求的 URL 是:
http://localhost:8080/api/users?id=389498473294
我希望它是
http://localhost:8080/api/users/389498473294
我可以使用$http
来做到这一点,但我认为.get()
应该能够做到...
谢谢
最佳答案
您可以使用前缀 @ 定义 id 参数的默认值,这意味着该值必须从作为参数传递给调用的对象中获取。在 get 调用中,没有发送对象,因此 id 参数被分配为 null 值。 由于 id 参数已分配,您传递的值将作为查询参数附加。 有关此问题的解释,请参阅 angular documentation在“用法/参数默认值”段落下。 正确的声明服务的方式应该是:
UserCtrl.factory('User', function($resource) { return $resource('/api/users/:id', { id: '' }, { update: { method: 'PUT' } }); });
关于angularjs - .get() 网址不是我所期望的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14813952/