Marco Riesco
Marco Riesco

Reputation: 511

Retriving item by id Firebase using AngularFire

I'm trying to search for an item with id, but I receive this message. All functions are working normally. When executed I get this error:

Storing data using array indices in Firebase can result in unexpected behavior. See https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase for more information.

MY FACTORY

.factory('TEST', function ($firebaseArray) {

    var ref = new Firebase('https://shark-firebase.firebaseio.com');

    return {
        all: function(section) {
            var data = $firebaseArray(ref.child(section));
            return data;
        },
        get: function(section, id) {
            var data = $firebaseArray(ref.child(section).child(id));
            return data;
        }
    };
});

I TRY TOGETHER:

        get: function(section, id) {
            var data = $firebaseArray(ref.child(section));
            return data.$getRecord(id);
        }

AND MY CONTROLLER:

in case, $stateParams.section = 'posts' and $stateParams.id = '0'.

$scope.loadItem = function(){
    $scope.item = TEST.get($stateParams.section, $stateParams.id);
};

Upvotes: 2

Views: 3510

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598857

Here is one way of getting that item:

var app = angular.module('app', ['firebase']);

app.factory('TEST', function ($firebaseArray, $firebaseObject) {

    var ref = new Firebase('https://shark-firebase.firebaseio.com');

    return {
        all: function(section) {
            var data = $firebaseArray(ref.child(section));
            return data;
        },
        get: function(section, id) {
            var data = $firebaseObject(ref.child(section).child(id));
            return data;
        }
    };
});

app.controller('MainCtrl', function($scope, TEST) {
    $scope.item = TEST.get('posts', 0);
});

See this jsbin for it working: http://jsbin.com/tumape/edit?html,js,output

But please read the page in the message you linked very carefully, because it points out some of the scalability-limiting problems in your current data structure.

  1. Using array indices on collections
  2. Nesting arrays

By ignoring such considerations it is probably easier to get started today, but you're limiting the extent to which your application will scale.

Upvotes: 5

Related Questions