0

I have a problema with Firebase Api and ref.on() method for list snapshot list. Look:

https://www.firebase.com/docs/web/guide/retrieving-data.html

Rooms factory:

.factory('Rooms', function ($firebaseObject, ObjectFactory) {
    var ref = new Firebase(firebaseUrl + '/rooms');

    var onComplete = function (error) {
        if (error) {
            console.log('Data could not be saved: ', error);
        }
        else {
            console.log('Data saved successfully!');
        }
    };

    return {
        all: function () {
            ref.on("value", function(snapshot) {
                return snapshot.val();
            }, function (errorObject) {
                console.log("The read failed: " + errorObject.code);
            });
        },

Controller:

.controller('RoomsCtrl', function ($scope, Rooms, $state) {
        var rooms = Rooms.all();

        console.log('All Rooms:', rooms);
        console.log('Rooms length:', rooms);

Output:

All Rooms: undefined
Rooms length: undefined

or:

Added $scope in my Rooms controller and:

all: function () {
            $scope.result = {};

            ref.on("value", function(snapshot) {
                $scope.result = snapshot.val();
            }, function (errorObject) {
                console.log("The read failed: " + errorObject.code);
            });

            return $scope.result;
        },

but the problem is continuos undefined and the new problem is present:

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- Room

I searched for already topic but I'm not finded nothing with this.

Returning undefined object from a firebase snapshot

Community
  • 1
  • 1
Francis Rodrigues
  • 1,470
  • 4
  • 25
  • 61

1 Answers1

0

There are a lot of problems with your code. First, Rooms.all() does not actually return anything. Second, Firebase calls are asynchronous, so you need to either use AngularFire, $q, or wrap your function in $timeouts.

Here's an example using $firebaseArray.

.factory('Rooms', function ($firebaseArray) {
    var ref = new Firebase(firebaseUrl + '/rooms');

    return {
        all: function () {
            return $firebaseArray(ref);
        },
     }
 })


.controller('RoomsCtrl', function ($scope, Rooms, $state) {
     var $scope.rooms = Rooms.all();
 });

By binding rooms to the scope, you can see the output in your view. However, if you really want to use console.log, you'll want to use $loaded() to log after data has been downloaded.

Anid Monsur
  • 4,538
  • 1
  • 17
  • 24