Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$rootScope.$apply() not working

I am doing an api call using angular service "AzureMobileClient " inside angular run method as follow:

myModule.run(function ($rootScope, $localStorage, AzureMobileClient, Data) {
//Return user json object; store it in Data.customerUserJsonObject
AzureMobileClient.getCustomerUser(function (item) {

    $rootScope.$apply(function () {
        Data.customerServerRowObject = item;
        console.log("rootScope applied");
    });

    console.log("myModule.run: item >");
    console.log(item);}, $localStorage.phonenumber);

});

Notice that I have a data sharing service "Data" passed to the run method to store the retrieved item from the api callback. The object "Data.customerServerRowObject" get set by the api call correctly. Also see the $rootScope.$apply() being called inside the callback to sync the object cross the angular application. Now, whenever I try to retrieve the object "Data.customerServerRowObject" in my controller I get "undefined" value:

controllers.OrderVarification = function ($scope, Data) {

// ng-model="customerPhonenumber" in the view
$scope.customerPhonenumber = Data.customerServerRowObject.phonenumber;

}

This is because the code inside the controller get executed while the api callback is still not done. I am also doing $rootSope.$apply() which has no effect in my run function

like image 432
Eyad Avatar asked Jun 12 '26 08:06

Eyad


1 Answers

You need to use promises, you can't convert an asynchronous operation in synchronous just by using $apply:

myModule.run(function ($rootScope, $localStorage, AzureMobileClient, Data, $q) {
//Return user json object; store it in Data.customerUserJsonObject
var deferred = $q.defer();
Data.customerServerRowObject = deferred.promise;
AzureMobileClient.getCustomerUser(function (item) {

    $rootScope.$apply(function () {
        deferred.resolve(item);
        console.log("rootScope applied");
    });

    console.log("myModule.run: item >");
    console.log(item);}, $localStorage.phonenumber);

});


controllers.OrderVarification = function ($scope, Data) {
  // ng-model="customerPhonenumber" in the view
  Data.customerServerRowObject.then(function(data){
     $scope.customerPhonenumber = data.phonenumber;
  });
}
like image 119
Wawy Avatar answered Jun 13 '26 22:06

Wawy