我似乎找不到从Firebase获取特定记录的方法

rus*_*nia 0 angularjs firebase angularfire

这是我为Firebase为应用程序构建的一项简单服务.我不得不对一些元素进行评审,我已经确定我使用的是最新版本的firebase和angular fire,因为它看起来变化很快.前几行很简单,

app.factory('Ship', function ($routeParams, $firebase, FIREBASE_URL) {

    var ref = new Firebase(FIREBASE_URL + 'ships');
Run Code Online (Sandbox Code Playgroud)

问题从这里开始.根据我打算对firebase对象做什么,有时它需要是$ asObject,有时则不是.这取决于教程,最近的教程似乎表明了这一点

    var shipsObj = $firebase(ref).$asObject(); // Is this necessary
    var ships = $firebase(ref);                // in the most modern version?

    var Ship = {
        all: shipsObj, // This works fine
        create: function (ship) {
            return shipsObj.$add(ship);  // This also works fine
        },
        find: function (shipId) {
            console.log($routeParams.shipId); // <--this ID appears as the correct numerical ID
Run Code Online (Sandbox Code Playgroud)

然后,接下来有六行,其中没有一行有效.它们都会产生错误,表明它们未定义.

            console.log(shipsObj.$child(shipId));
            console.log(ships.$child(shipId));
            console.log(shipsObj.$getRecord(shipId));
            console.log(ships.$getRecord(shipId));
            console.log(ships.$keyAt(shipId));
            console.log(shipsObj.$keyAt(shipId));
        },
Run Code Online (Sandbox Code Playgroud)

我不会厌倦你多次重复下一个方法,但$remove也没有工作.

        delete: function (shipId) {
            return ships.$remove(shipId);
        }
    };

    return Ship;
Run Code Online (Sandbox Code Playgroud)

});

rob*_*rob 6

假设您使用AngularFire的v0.8,您将需要使用$asObject()$asArray()获取实际数据.这是官方博客文章,讨论了v0.8中的变化:https://www.firebase.com/blog/2014-07-30-introducing-angularfire-08.html

因此,要通过其ID访问船舶,您可以执行以下操作:

var shipsObj = $firebase(ref).$asObject();
console.log(shipsObj[shipId]);
Run Code Online (Sandbox Code Playgroud)

您可能还想查看AngularFire的API文档:https://www.firebase.com/docs/web/bindings/angular/api.html

v0.8发生了很大变化,它刚刚问世(2014年7月),所以如果你的代码基于比那些更旧的东西那么它可能不会工作