简体   繁体   中英

Firebase retrieve Object by Key in JavaScript Api

Help:

I'm an object of Firebase and can not recover only one item from the list because the key is a objectId and the doc api JS Firebase, it does not have a method to recover for me.

Can you help me?

Controller

var rooms = Rooms.all();

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

        // New test room
        if (!rooms) {
            var objRooms = [
                {
                    cc: 'Business 1',
                    name: 'Chat 1',
                    city: 'Curitiba',
                    state: 'PR'
                },
                {
                    cc: 'Business 2',
                    name: 'Chat 2',
                    city: 'Floripa',
                    state: 'SC'
                }
            ]

            var objRoom = Rooms.save(objRooms);
            console.log('ROOMID: ', objRoom.key());
        }

Service

.factory('Rooms', function ($firebaseObject) {
        // Might use a resource here that returns a JSON array
        var ref = new Firebase(firebaseUrl);
        var rooms = $firebaseObject(ref.child('rooms'));

        return {
            all: function () {
                return rooms;
            },
            get: function (roomId) {
                // Simple index lookup

                console.log('ROOMD:', rooms);

                return rooms[ ref.child(roomId) ];
            },
            save: function (roomData) {
                var obj = ref.child('rooms');

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

                return obj.push(roomData, onComplete);
            }
        }
    })

Output:

Chat Controller initialized!
controllers.js:117 Object {params: Object, current: Object, $current: extend, transition: null}$current: extendcurrent: Objectget: (stateOrName, context)go: go(to, params, options)href: href(stateOrName, params, options)includes: includes(stateOrName, params, options)is: is(stateOrName, params, options)params: ObjectroomId: "-JxlCvzgbdkQfoA1Of78"__proto__: Objectreload: reload()transition: nulltransitionTo: transitionTo(to, toParams, options)__proto__: Object
services.js:78 Selecting the room with id: -JxlCvzgbdkQfoA1Of78
services.js:20 ROOMD: d {$$conf: Object, $id: "rooms", $priority: null}
app.js:43 Logged in as : simplelogin:2

The factory Rooms is a problem:

get: function (roomId) {
            // Simple index lookup

            console.log('ROOMS:', rooms);
            console.log('ROOM specified:', ref.child(roomId).key());

            return rooms[ ref.child(roomId) ];
        },

[Update]

I created the factory Objects for filter Object data:

.factory('Objects', function () {
        return {
            filter: function (objectValues, objectKey) {
                // to take an action after the data loads, use the $loaded() promise
                objectValues.$loaded().then(function () {
                    // To iterate the key/value pairs of the object, use angular.forEach()
                    angular.forEach(objectValues, function (value, key) {
                        if (key === objectKey) {
                            console.log(objectValues[objectKey]);
                            return objectValues[objectKey];
                        }
                    });
                });
            }
        }
    })

and Rooms factory, I edited method get and set:

get: function (roomId) {
     return Objects.filter(rooms, roomId);
},

[Update] I have a database based in the image:

在此处输入图片说明

I need list object data.

JavaScript Api

https://www.firebase.com/docs/web/api/

First of all you should use Angularfire which provides some useful methods for using Firebase with AngularJS. You can find the documentation here:

https://www.firebase.com/docs/web/libraries/angular/api.html

Now, your question is how to access an single item using it's key. You can do that simply by just providing the url to that object when retrieving either a $firebaseArray or $firebaseObject (when using Angularfire API):

http://myfirebase.firebase.io/blazing-heat-9118/rooms/ + roomId

And then pass this url to a new Firebase() call:

var ref = new Firebase('http://myfirebase.firebase.io/blazing-heat-9118/rooms/' + roomId);

var room = $firebaseObject(ref);

  // To take an action after the data has finished loading, use the $loaded() promise
obj.$loaded().then(function(res) {

  console.log(res); // res will be the room object

  // To iterate the key/value pairs of the object, use angular.forEach()
  angular.forEach(obj, function(value, key) {
    console.log(key, value);
  });
});

Now you will have fetched the single room from the database.

I'd suggest reading through the Angularfire documentation thoroughly as it contains some great methods for handling your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM