Recover Firebase Object value

Asked

Viewed 297 times

0

Hello,

I’m having trouble recovering the value of an Object in the Firebase Database.

I have the following object on the base:WordDetail

I wanted to recover in case the value of lastId(108) for later, when saving to the Objects list Words have the last id +1. (This information will be used as a database quence, because the list of Words will serve to feed an Android app)

I made the code below:

var words = firebase.database().ref('Words/');
const list = $firebaseArray(words);

$scope.addWord = function (word) {
    var id;
    var wdRef = firebase.database().ref('WordsDetail');
    wdRef.on('value', function(snap) {
        id = snap.val().lastId;
    });

    words.push({
        //idWord: list.length + 1,
        idWord: id,//quero usar o id que recuperei aqui!
        word: word.word,
        description: word.description
    });

    delete $scope.word;
    $scope.wordForm.$setPristine();

}

But the variable id does not take the value.

Would anyone know how to do that?

1 answer

1


Hello, just for the record.

I used #Scope to control the information lastId, loading as soon as the screen is started, and updating it whenever a new record is inserted.

The final code went like this:

var words = firebase.database().ref('Words/');
const list = $firebaseArray(words);

var wdRef = firebase.database().ref('WordsDetail/');

loadLastId();

$scope.addWord = function (word) {
    var id = $scope.lastId;
    words.push({
        idWord: id,
        word: word.word,
        description: word.description
    });

    wdRef.set({
        lastId: id + 1
    });

    loadLastId();

    delete $scope.word;
    $scope.wordForm.$setPristine();

}

function loadLastId() {
    //Preenchendo escopo com o ultimo id
    var wdObj = $firebaseObject(wdRef);

    wdObj.$loaded().then(function() {
        $scope.lastId = wdObj.lastId;
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.