Javascript 理解$resource工厂和@prefix
提供以下服务:Javascript 理解$resource工厂和@prefix,javascript,angularjs,rest,url-parameters,ngresource,Javascript,Angularjs,Rest,Url Parameters,Ngresource,提供以下服务: vdgServices.factory('UserService',['$resource',', 职能(资源){ 返回$resource('api/users/:id',{}{ 多吉特:{ 方法:“GET”, 参数:{id:'@userId'} }, doPost:{ 方法:“POST”, 参数:{id:'@userId'} }, 多普特:{ 方法:'放', 参数:{id:'@userId'} }, 多德莱特:{ 方法:“删除”, 参数:{id:'@userId'} } });
vdgServices.factory('UserService',['$resource',',
职能(资源){
返回$resource('api/users/:id',{}{
多吉特:{
方法:“GET”,
参数:{id:'@userId'}
},
doPost:{
方法:“POST”,
参数:{id:'@userId'}
},
多普特:{
方法:'放',
参数:{id:'@userId'}
},
多德莱特:{
方法:“删除”,
参数:{id:'@userId'}
}
});
}]);
我遵守以下请求的URL:
var-params={userId:42};
var onSuccess=function(){console.log(“OK”);};
var onError=function(){console.log(“KO”);};
doGet(params、onSuccess、onError);
//请求api/用户?用户ID=42
doPost(参数、onSuccess、onError);
//请求api/users/42
doPut(参数、onSuccess、onError);
//请求api/users/42
doDelete(params、onSuccess、onError);
//请求api/用户?用户ID=42
有谁能解释一下为什么:id
URL参数有时会被42
替换,有时则不会
理想情况下,我希望任何方法都可以替换它,即每次请求的URL都变成“api/users/42”。AngularJS$resource
如果参数值的前缀为@,则该参数的值将取自数据对象上的相应键(对非GET操作有用)
您将params放错了位置,应该这样实现
.factory('UserService', function($resource) {
return $resource('api/users/:id', { id: '@id' }, {
doGet: {
method: 'GET'
},
doPost: {
method: 'POST'
},
doPut: {
method: 'PUT'
},
doDelete: {
method: 'DELETE'
}
});
});
让我们测试一下
jsfiddle:
describe('userApp', function () {
var UserService
, $httpBackend
;
beforeEach(function () {
module('userApp');
});
beforeEach(inject(function (_UserService_, _$httpBackend_) {
UserService = _UserService_;
$httpBackend = _$httpBackend_;
}));
describe('User resource - api/users', function () {
it('Calls GET – api/users/{id}', function() {
$httpBackend.expectGET('api/users/42').respond(200);
UserService.doGet({id: 42});
$httpBackend.flush();
});
it('Calls POST - api/users/{id}', function() {
$httpBackend.expectPOST('api/users/42').respond(200);
UserService.doPost({id: 42});
$httpBackend.flush();
});
it('Calls PUT - api/users/{id}', function() {
$httpBackend.expectPUT('api/users/42').respond(200);
UserService.doPut({id: 42});
$httpBackend.flush();
});
it('Calls DELETE - api/users/{id}', function() {
$httpBackend.expectDELETE('api/users/42').respond(200);
UserService.doDelete({id: 42});
$httpBackend.flush();
});
});
});