如何扩展AngularJS资源($资源)的构造函数?

我有一个模型,使用$资源定义,我正在成功加载.

如所承诺的,每个加载的实例都是我定义的类的一个实例.

(下面的例子来自Angular文档,在其中,User.get导致一个objectof User的对象.)

var User = $resource('/user/:userId',{userId:'@id'});

但是,想像一下每个用户如下所示:

{
  "username": "Bob","preferences": [
    {
      "id": 1,"title": "foo","value": false
    }
  ] 
}

我定义了一个Preference工厂,为Preference对象添加了有价值的方法.但是当用户加载时,这些首选项自然不是首选项.

我试过这个:

User.prototype.constructor = function(obj) {
  _.extend(this,obj);
  this.items = _.map(this.preferences,function(pref) {
    return new Preference(pref);
  });
  console.log('Our constructor ran'); // never logs anything
}

但它没有任何效果,也不会记录任何东西.

我如何使用户的首选项数组中的每个项目都是首选项的实例?

$资源是一个简单的实现,缺少这样的东西.

User.prototype.constructor不会做任何事情;与其他库不同,角度不会像面向对象那样尝试行事.这只是javascript

不幸的是,你有承诺和javascript :-).这是一种你可以做的方法

function wrapPreferences(user) {
  user.preferences = _.map(user.preferences,function(p) {
    return new Preference(p);
  });
  return user;
}

var get = User.get;
User.get = function() {
  return get.apply(User,arguments).$then(wrapPreferences);
};
var $get = User.prototype.$get;
User.prototype.$get = function() {
  return $get.apply(this,arguments).$then(wrapPreferences);
};

您可以将其抽象为一种装饰资源方法方法:它需要一个对象,一个方法名称数组和一个装饰器函数.

function decorateResource(Resource,methodNames,decorator) {
  _.forEach(methodNames,function(methodName) {
    var method = Resource[methodName];
    Resource[methodName] = function() {
      return method.apply(Resource,arguments).$then(decorator);
    };
    var $method = Resource.prototype[methodName];
    Resource.prototype[methodName] = function() {
      return $method.apply(this,arguments).$then(decorator);
    };
  });
}
decorateResource(User,['get','query'],wrapPreferences);

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...