$ rootScope。$ apply()无效

时间:2015-02-10 17:09:13

标签: javascript angularjs

我在角度运行方法中使用角度服务“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回调的检索项。 对象“Data.customerServerRowObject”由api调用正确设置。另请参阅$ rootScope。$ apply()在回调中调用,以跨越角度应用程序同步对象。现在,每当我尝试在控制器中检索对象“Data.customerServerRowObject”时,我都会得到“未定义”值:

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

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

}

这是因为控制器内的代码在api回调仍未完成时执行。我也在做$ rootSope。$ apply()这对我的运行函数没有影响

1 个答案:

答案 0 :(得分:2)

你需要使用promises,你不能只使用$ 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;
  });
}
相关问题