添加带有下划线前缀的属性的对象

时间:2016-11-07 22:53:54

标签: firebase firebase-realtime-database angularfire

我想在Firebase数据库中添加包含前缀为_的属性的对象。

保存时似乎只会忽略这些属性。

我的代码看起来像这样,工作正常:

.config(function($provide) {
    $provide.decorator('$firebaseArray', function($delegate, $window) {
        var add, timestamp, currentUser;

        add = $delegate.prototype.$add;
        timestamp = $window.firebase.database.ServerValue.TIMESTAMP;
        currentUser = $window.firebase.auth().currentUser.uid;

        $delegate.prototype.$add = function (newData) {
            //works if remove '_'
            newData['_createdAt'] = timestamp;
            newData['_createdBy'] = currentUser;

            return add.call(this, newData);
        };

        return $delegate;
    });
})

.config(function($provide) {
    $provide.decorator('$firebaseObject', function($delegate, $window) {
        var save, timestamp, currentUser;

        save = $delegate.prototype.$save;

        timestamp = $window.firebase.database.ServerValue.TIMESTAMP;
        currentUser = $window.firebase.auth().currentUser.uid;

        $delegate.prototype.$save = function () {
            //works if remove '_'
            this['_modifiedAt'] = timestamp;
            this['_modifiedBy'] = currentUser;

            return save.call(this);
        };

        return $delegate;
    });
})

1 个答案:

答案 0 :(得分:1)

之所以这是因为AngularFire内置方法$firebaseUtils.toJSON会删除一些前缀属性。

我解决了将.toJSON()添加到对象模型的问题。

MyObject.prototype = {
    toJSON: function () {
        return angular.copy(this);
    }
};