S
S
Sergey2019-09-12 11:14:31
Angular
Sergey, 2019-09-12 11:14:31

How to correctly run an asynchronous function from a service?

Good afternoon. There is a service with a function that loads information from the database.

function getData($http) { 
         this.users = async function(){
            const connect = await $http.get('http://localhost:3000/getUsers')
            const data = await connect.data
            return data   
        } 
    }

There is a task, simply to show the information from a DB in div. The service function is called from the main controller.
function MainCtrl($scope,$rootScope,$log,getDataServis, $http){
    const vm = this
 
   getDataServis.users()
   .then((res,rej)=>{
       vm.arr = res
   })
   vm.arr = (getDataServis.users())
  
   
    vm.clickFunction = function(name){
        console.log('hi')
    }

An interesting situation, if you remove the line vm.arr = (getDataServis.users()), in the application, data from the database appears after pressing the button with the function vm.clickFunction. If you leave the line, first an empty object {} appears in the application, and then the information itself.
Please briefly explain under the hood how angularjs works and how to avoid the above problems
. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2019-09-12
@Banjamin

The solution is the following:

getDataServis.users()
   .then((res,rej)=>{
       vm.arr = res;
       $scope.$digest()
       
   })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question