How to make the URL of $resource generic?
I am new to AngularJS and I have a question here.
I am using $resource
for my CRUD actions.
I currently have the code like this,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource) {
return $resource("api/UserRoleApi", {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
//below is the code in my controller
UserRoleService.query(function (data) {
vm.UserRoleLookups = data;
});
I would like to make my UserRoleService
generic, which means I don't want to provide the specific URL for the API in the factory level.
I now modify my code a little bit,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource, url) {
return $resource(url, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
My question is what I should do in my controller?
So, instead of directly returning $resource
, we can encapsulate it with a function that accepts url
as a param.
Something like this:
myApp.factory('UserRoleService', function($resource) {
return {
query: function(url) {
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
},
get: {
method: "GET"
}
});
}
}
});
Now, in controller, you can call it like:
UserRoleService.query('//httpbin.org').get()
example fiddle
链接地址: http://www.djcxy.com/p/89560.html上一篇: mongoose.model的实例没有find方法
下一篇: 如何使$资源的URL通用?