gpt4 book ai didi

javascript - 了解 $resource 工厂和 @ 前缀

转载 作者:行者123 更新时间:2023-12-03 12:09:08 25 4
gpt4 key购买 nike

给定以下服务:

vdgServices.factory('UserService', ['$resource',
function($resource) {

return $resource('api/users/:id', {}, {

doGet: {
method: 'GET',
params: { id: '@userId' }
},

doPost: {
method: 'POST',
params: { id: '@userId' }
},

doPut: {
method: 'PUT',
params: { id: '@userId' }
},

doDelete: {
method: 'DELETE',
params: { id: '@userId' }
}

});

}]);

我观察到以下请求的 URL:

var params = { userId: 42 };
var onSuccess = function() { console.log("OK"); };
var onError = function() { console.log("KO"); };

UserService.doGet(params, onSuccess, onError);
// requests api/users?userId=42

UserService.doPost(params, onSuccess, onError);
// requests api/users/42

UserService.doPut(params, onSuccess, onError);
// requests api/users/42

UserService.doDelete(params, onSuccess, onError);
// requests api/users?userId=42

谁能解释为什么 :id URL 参数有时会被 42 替换,有时不会?

理想情况下,我希望它可以替换为任何方法,即请求的 URL 每次都变为“api/users/42”。

最佳答案

AngularJS $资源

If the parameter value is prefixed with @ then the value of that parameter will be taken from the corresponding key on the data object (useful for non-GET operations).

你把参数放在了错误的地方,你应该像这样实现

.factory('UserService', function($resource) {
return $resource('api/users/:id', { id: '@id' }, {

doGet: {
method: 'GET'
},

doPost: {
method: 'POST'
},

doPut: {
method: 'PUT'
},

doDelete: {
method: 'DELETE'
}

});
});

让我们测试一下

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

jsfiddle:http://jsfiddle.net/krzysztof_safjanowski/vbAtL/

关于javascript - 了解 $resource 工厂和 @ 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25044469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com