如何从服务中调用角度资源

时间:2013-08-26 06:45:02

标签: angularjs

我正在使用Angular 1.1.5(等待angular-ui-router与1.2.0兼容)。我定义了资源和服务:

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

在我的控制器中,我尝试了queryquery1,但他们都返回Cannot call method 'then' of undefinedquery2应该是调用资源的1.2.0方式。

编辑:更新了控制器

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

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

EDIT2:

我按照建议尝试了

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会返回一个承诺,您可以在该承诺上致电$then而不是then,然后就可以了。

query4会返回错误Object #<Resource> has no method 'query'。我使用new的原因是传递参数(这是它的记录方式):另见Angular resource REST has no method '$save'

1 个答案:

答案 0 :(得分:0)

在控制器中注入服务,例如;

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

希望它有所帮助。