加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:47:02 所属栏目:安全 来源:网络整理
导读:我有一个模型,使用$资源定义,我正在成功加载. 如所承诺的,每个加载的实例都是我定义的类的一个实例. (下面的例子来自Angular文档,在其中,User.get导致一个objectof User的对象.) var User = $resource('/user/:userId',{userId:'@id'}); 但是,想像一下每个用
我有一个模型,使用$资源定义,我正在成功加载.

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

(下面的例子来自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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读