AngularFire,使用'无效密钥$ id(不能包含。$ []#)'扩展$ firebaseArray保存错误

时间:2016-03-16 03:45:02

标签: firebase angularfire

扩展$ firebaseArray时,我收到错误'无效密钥$ id(不能包含。$ []#)'

问题在于book对象上的$ id属性。当在数组上调用$ save并传入修改后的book时,工厂不会像扩展之前那样将$ id识别为id字段。

HTML

<ul>
    <li ng-repeat="book in bookList"> <a href="#" ng-click="loadBook(book)">{{book.$id}}: {{book.date|date:"medium"}}</a> 
        <button ng-click="setDate(book)">set date</button>
    </li>
</ul>
<pre>{{book|json}}</pre>

的Javascript

// reference to our Firebase instance
var fb = new Firebase('YourUrl');

function Book(snap) {
    // records in synchronized arrays must have a $id property
    this.$id = snap.key();
    this.update(snap);
}

Book.prototype.update = function (snap) {
    angular.extend(this, snap.val());
    // convert json dates to Date objects
    this.date = new Date(this.date||0);
    this.$priority = snap.getPriority();
};

Book.prototype.toJSON = function() {
    return angular.extend({}, this, {
        // revert Date objects to json data
        date: this.date.getTime()
    });
};

var app = angular.module('app', ['firebase']);
app.controller('ctrl', function ($scope, bookFactory) {    
    // create a synchronized array with a customized version 
    // of $FirebaseArray

    $scope.bookList = new bookFactory(fb);


    // loads a single record for display
    $scope.book = "Click on a book id";
    $scope.loadBook = function (book) {
        $scope.book = book;
    };

    // changes the date on a book record, note that we're working
    // with Date objects here
    $scope.setDate = function(book) {
        book.date = new Date();
        $scope.bookList.$save(book);
    };
});

app.factory('bookFactory', function ($firebaseArray, $firebaseUtils) {
    return $firebaseArray.$extend({
        // override $$added to return a Book object
        $$added: function (snap, prevChild) {
            return new Book(snap);
        },

        // override $$updated to update the book object
        $$updated: function (snap) {
          var rec = this.$getRecord(snap.name());
          if(angular.isObject(rec) ) {
            book.update(snap);
          }
        }
    });
});

制作一个显示错误的小提琴,只需在任何一本书上按“设定日期”即可。 https://jsfiddle.net/jensenben/h98mjsoz/

如果让book对象使用id而不是$ id并将$ getKey方法添加到$ extend调用以告诉它哪个字段中包含id,可以解决这个问题,但我更喜欢坚持使用我没有扩展$ firebaseArray时使用的传统$ id字段。

function Book(snap) {
    // records in synchronized arrays must have a $id property
    this.id = snap.key();
    this.update(snap);
}

return $firebaseArray.$extend({
    $$getKey: function(rec) {
        return rec.id;
    },
...

1 个答案:

答案 0 :(得分:1)

有一点很多,所以我不确定这是不是你的问题。但要消除错误,请在保存时将$firebaseObject()转换为常规JSON对象:

$scope.setDate = function(book) {
    book.date = new Date();
    $scope.bookList.$save(book.toJSON());
};

请注意,CSS和大多数JavaScript代码与问题无关。