Page loads before firebase data returns.

Asked

Viewed 25 times

0

I am with a controller, where I search data firebase, but when doing this search the code suffers 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 db.Collection comes filled after the search suffering a delay. Thus in the HTML page the data is not shown.

Any hint?

1 answer

1

The db.collection("jedi").get() returns to you a Promise which is an asynchronous datum and which will not actually appear immediately. Through the .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 the rendering of your HTML. My suggestion is that you create an animation of loading HTML pro that starts before fetching 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;
    });
}

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

Browser other questions tagged

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