質問

I'm developing angular web app. And I have this controller which needs to call restful api to do some operations on Users.

Earlier I'm thinking define a service which has some methods: getAllUser( ), getUser(id), saveUser( ), deleteUser( ). these methods will use a ngResource to call rest apis. But when I look at these methods, it seems to me that I'm just wrapping the ngResource and expose some of his lower level methods: query( ), get( ), save( ), delete( ).

Could someone share some experience about how will you design common services or factories or providers which use ngResource to fetch data from server?

役に立ちましたか?

解決 2

Let me explain about ngResource...

ngResource is a service from AngularJs and it use at lower lever the $http service, so its very simple to use it when you want to use the RESTFul Resources. Here is my example:

myAppModule.factory('User', ['$resource', function($resource) { 
        return $resource('/user/:userId'}
]);

So what this code above are doing? This is creating a service that return a resource, the url was mapped, so when you inject and call this service you receive a object with some methods: "GET", "POST", "PUT", "DELETE"... Example:

var users = User.query();

The variable "users", receive all users(and plus it receive some resource features like save, because "users" variable still being a resource object), it's like you make this request (.../user/), ok? All you have to do is call resource, it's very simple.

他のヒント

I've been working on an angular project myself. And I'd built a Factory manually, and then ended up using JBoss Forge for my second attempt and that build stuff for me in a pretty nice way, here's what it looked like:

angular.module('myApp').factory('myResource', function($resource){

    var urlBase = '/rest/resources';

    var resource = $resource(urlBase + '/:RsvpId',{RsvpId:'@id'},{'queryAll':{method:'GET',isArray:true},'query':{method:'GET',isArray:false},'update':{method:'PUT'}});

    return resource;
});

That's all there is to it, then when you want to call it, you do something like the following:

$scope.save = function() {
    var successCallback = function(data,responseHeaders){
        var id = locationParser(responseHeaders);
        $location.path('/Resources/edit/' + id);
        $scope.status = 'success';
    };
    var errorCallback = function(data, status, headers, config) {
        $scope.status = 'failure';
        $scope.statusMessage = 'Saving your resource failed: ' + $scope.errorMessage;
    };
    myResource.save($scope.resource, successCallback, errorCallback);
};

or to do a get, you'd have this line inside a method:

myResource.get({ResourceId:$routeParams.ResourceId}, successCallback, errorCallback);

or

resource.$remove(successCallback, errorCallback);

Hope that helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top