如何使用REST(使用$ resource)和其他更多方法定义AngularJs服务

时间:2014-08-18 13:16:12

标签: javascript angularjs rest

除了我已经拥有的REST方法之外,我想在相同的设置服务上定义更多方法。 我不知道怎么做。

 var settingsService = angular.module('settingsService',['ngResource']);

 settingsService.service('SettingsService', ['$resource', function($resource){
    return $resource('http://localhost:9000/settings', {}, {
        update: {method:'PUT'},
    });
}]);

如何为此服务添加更多方法和成员? 例如:

 var settingsService = angular.module('settingsService',['ngResource']);

 settingsService.service('SettingsService', ['$resource', function($resource){
    return $resource('http://localhost:9000/settings', {}, {
        update: {method:'PUT'},
    });

  var x; //some member

  this.func1 = function(){
     // do something
  }
}]);

由于

2 个答案:

答案 0 :(得分:0)

你可以这样写

settingsService.service('SettingsService', ['$resource', function($resource){

   var _settingsServiceFactory = [];

   var _varX = 'someValue';
   var _functionX = function() { // do something };

    var _resourceSrvc = function() {
    return  $resource('http://localhost:9000/settings', {}, {
        update: {method:'PUT'}});

    settingsServiceFactory.VarX  = _varX;
    settingsServiceFactory.FunctionX  =_functionX ; 
settingsServiceFactory.ResourceSrvc  = _resourceSrvc;

return settingsServiceFactory;
});

或者简单地写

settingsService.service('SettingsService', ['$resource', function($resource){

var _settingsServiceFactory = {

FunctionX = function() { // do something },
ResourceSrvc = function() {
        return  $resource('http://localhost:9000/settings', {}, {
            update: {method:'PUT'}});

};

return _settingsServiceFactory 

});

要么你做同样的事情。

答案 1 :(得分:0)

考虑到您的编辑,这是您添加更多功能的一种方式

var settingsService = angular.module('settingsService',['ngResource']);

 settingsService.service('SettingsService', ['$resource', function($resource){
//use a variable to hold the resource object
var settingsUpdater = $resource('http://localhost:9000/settings', {}, {
    update: {method:'PUT'}
});

   //declare the other functions you want
function doX()
{
  //do something
}

function doY(args)
{
 //do something with args
}

//after declaring all your functions you can return a hash of them

return
{
   //the key will be what you invoke using SettingsService and you can call it what you like. I will call it invokedoX....yes I suck at naming

   invokedoX:function()
   {
      doX();
   },
   invokedoY:function(args)
   {
      doY(args);
   },
   //your resource object

   updateSettings:function(successCallback,errorCallback){
     //settingsUpdater is what I called it above
     settingsUpdater.update(successCallback,errorCallback);
   }
}

}]);

对于您的资源对象,数据将在控制器或指令中的successCallback中返回,或者在您注入服务的任何位置返回。请注意,successCallback看起来像

function(data)
{
}

并且错误回调看起来像

function(error)
{
}

所以在你的控制器中,它看起来像

SettingsService.updateSettings(function(data){}, function(error){});

希望这会给你一个良好的开端。