2

I am using Angular 1.1.5 (wait for angular-ui-router to be comptabible with 1.2.0). I defined a resource and a service:

myapp.factory( 'Monitoring', function($resource) {
   return $resource('/webapp/network/v1/cronjobs/:id/:action', { id: '@id' }, {
       status: { method: 'PATCH', headers:{'Content-Type': 'application/json'}, params:{action: 'status'}}
   }
 );
});

myapp.factory('MonitoringCRUDControllerService', ['Monitoring', '$state', function(Monitoring, $state) {
    return {
        query: function() {
            var m = new Monitoring();
            var promise = m.$query().then(function(response) {
                console.log(response);
                return response.data;
            });
            return promise;
        },
        query1: function() {
            var m = new Monitoring();
            return m.$query();
        },
        // Angular 1.2.0 RC
        query2: function() {
            var m = new Monitoring();
            return m.$query().$promise;
        }       
    }
}]);

In my controller I tried query and query1 but both of them returned Cannot call method 'then' of undefined. The query2 should be the 1.2.0 way to call the resource.

EDIT: Updated controller

function($scope, $location, MonitoringCRUDControllerService) {
    $scope.refresh = function() {
        MonitoringCRUDControllerService.query().then(function(value) {
            $scope.myData = value;
        });
    };
}

console.log(MonitoringCRUDControllerService) returns Object {create: function, get: function, query1: function, query2: function, update: function…}

EDIT2:

I tried as suggested

query3: function() {
    return Monitoring.query();
},
query4: function() {
    var m = new Monitoring();
    var promise = m.query().then(function(response) {
        console.log(response);
        return response.data;
    });
    return promise;
},

query3 returns a promise on which you can call $then and not then and it works.

query4 returns an error Object #<Resource> has no method 'query'. The reason I used the new is for passing arguments (this is how it's documented): See also Angular resource REST has no method '$save'

Community
  • 1
  • 1
Sydney
  • 11,964
  • 19
  • 90
  • 142

1 Answers1

0

Inject the service in your controller like;

yourApp.controller('ControllerName',function(MonitoringCRUDControllerService){
    $scope.refresh = function() {
        MonitoringCRUDControllerService.query().then(function(value) {
            $scope.myData = value;
        });
    };
});

Hope it helps.

BKM
  • 6,949
  • 7
  • 30
  • 45
  • It was already done, the error is on the `then`, so it means the query is executed, but the returned object is undefined. – Sydney Aug 26 '13 at 06:55
  • Try changing the function name from query to something else, say 'get' and call it like MonitoringCRUDControllerService.get(); – BKM Aug 26 '13 at 06:57