Javascript $rootScope.$apply()不工作

Javascript $rootScope.$apply()不工作,javascript,angularjs,Javascript,Angularjs,我在angular run方法中使用angular服务“AzureMobileClient”进行api调用,如下所示: myModule.run(function ($rootScope, $localStorage, AzureMobileClient, Data) { //Return user json object; store it in Data.customerUserJsonObject AzureMobileClient.getCustomerUser(function (it

我在angular run方法中使用angular服务“AzureMobileClient”进行api调用,如下所示:

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);

});
请注意,我将数据共享服务“data”传递给run方法,以存储从api回调中检索到的项。 api调用正确设置了对象“Data.customerServerRowObject”。另请参见在回调中调用$rootScope.$apply(),以跨角度应用程序同步对象。现在,每当我尝试在控制器中检索对象“Data.customerServerRowObject”时,我都会得到“undefined”值:


这是因为控制器中的代码在api回调尚未完成时执行。我也在做$rootSope.$apply(),它对我的run函数没有任何影响

你需要使用promissions,你不能仅仅使用$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;
  });
}

run块不会等待
getCustomerUser
函数完成,因此我猜测控制器代码是在设置
Data.customerServerRowObject
之前执行的。因此,当控制器复制
phonenumber
时,它是
未定义的
。还要注意的是,由于
phonenumber
是一个原语,它的值被复制到
customerPhonenumber
中。以后对
customerPhonenumber
的更新将不会更新
phonenuber
的值。最佳做法:使用
$timeout
而不是
$rootScope.$apply()
以避免难以调试的错误“摘要已在进行中”您不应该对以下内容使用$timeout:(1)按目的具有超时(2)的业务逻辑代码的异步行为。依靠固定的时间不仅效率低下,而且不可靠。
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;
  });
}