Page loads before the firebase data returns.

0

I'm having a controller, where I look for data from the firebase, but when doing this search the code undergoes a delay and the page is loaded before with empty data before the query actually ends.

My controller:

function DashboardController($http, $scope){

    var vm = this;
    vm.searchJedi = searchJedi;
    vm.obj = [];
    vm.jedi = {
        master: '',
        name: '',
        planet: '',
        status
    }
    vm.teste = [];

   vm.searchJedi();

    function searchJedi(){
        db.collection("jedi").get().then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                vm.jedi = doc.data();
                vm.obj.push(vm.jedi);
            });
            console.log(vm.obj); //objeto com valor
        });

        console.log(vm.obj); //objeto vazio 
    }
}

What happens is that this last console is always empty while the console that is inside the db.collection is populated after the search undergoing a delay. That way in the HTML page the data is not shown.

Any tips?

    
asked by anonymous 12.10.2018 / 19:57

1 answer

1

The db.collection("jedi").get() returns to you a Promise which is an asynchronous data and that will not really appear right away. Through .then you get the value and while it is running the rest of the external code it is also following, such as your console.log that is empty and rendering your HTML. My suggestion is that you create a loading HTML animation that starts before fetching the data with db.collection and ends after its inclusion in vm.obj.push(vm.jedi) . Example:

var loading;
function searchJedi(){
    loading = true;
    db.collection("jedi").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            vm.jedi = doc.data();
            vm.obj.push(vm.jedi);
        });
        loading = false;
    });
}

As this loading is treated in HTML to appear like this: <div ng-if="loading ">Carregando...</div>

    
15.10.2018 / 05:46