Retrieve Firebase Object Value

0

Hello,

I'm having trouble retrieving the value of an Object in Firebase Database.

I have the following object in base:

I would like to retrieve the value of lastId (108) and then save it in the list of Words objects with the last id +1. used as a sequence of the database, because the list of Words will serve to feed an Android app)

I made the following code:

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 hold the value.

Would anyone know how to do this?

    
asked by anonymous 27.10.2017 / 16:32

1 answer

1

Hello, just to register that I was able to solve the problem.

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

The final code looks 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;
    });
}
    
30.10.2017 / 15:36