0

Inside my $onInit function I have two functions that fetch data. I use third function where I need the data from the first two. The logic that I do in third function is what will be rendered on the screen. How do I use callback in $onInit and make sure that the third function is not run before the first two?

 ctrl.$onInit = $onInit;

    function $onInit() {
        getFood();
        getDrinks();

        combineFoodAndDrinks();
    }

EDIT MY CODE EXAMPLE

 var ctrl = this;
 ctrl.company = {};
 ctrl.company.administrators = [];
 ctrl.administrators = [];
 ctrl.$onInit = $onInit;
 ....

function $onInit() {
        $q.all([getCompanies(), getAdministrators()]).then(findAdministrators);
        getUnasignedAdministrators();
    }

    function getCompanies() {
        companiesService.getCompanies()
            .then(function (data) {
                var company = data.items.find(function (company) {
                    if ($stateParams.id === company.id) {
                        return company;
                    }
                });
                ctrl.company.name = company.name;
                ctrl.company.contactPerson = {
                    firstName: company.contactPersonName,
                    lastName: company.contactPersonLastName,
                    phone: company.contactPersonPhone
                };
            })
            .catch(function (response) {
                responseService.displayError(response);
            });
    }

    function getAdministrators() {
        administratorsService.getAdmins()
            .then(function (data) {
                ctrl.administrators = data.items;
            })
            .catch(function (response) {
                responseService.displayError(response);
            });
    }

    function findAdministrators() {
        console.log("getCompanies", ctrl.company);
        console.log("getAdministrators", ctrl.administrators);
    }
Igor-Vuk
  • 3,551
  • 7
  • 30
  • 65

1 Answers1

0

You should rather consider returning promise from getFood & getDrinks method and call combineFoodAndDrinks on completion of those two method promise. In general the code snippet will look like below.

ctrl.$onInit = $onInit;

function getFood(){
   return $http.get('getFoodurl')
}

function getDrinks(){
   return $http.get('getDrinksurl')
}

function combineFoodAndDrinks(data){
   console.log("getFood data", data[0])
   console.log("getDrinks data", data[1])
}

function $onInit() {
    $q.all([getFood(), getDrinks()]).then(combineFoodAndDrinks);
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thanks Pankaj. I tried it but I still can not mkae it work. I added my code in first post. Administrators alwas return empty array but I get back companies. – Igor-Vuk Aug 06 '17 at 21:22