javascript - $rootScope.$apply() 不工作

标签 javascript angularjs

我在 Angular 运行方法中使用 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 回调中检索到的项目。 对象“Data.customerServerRowObject”通过 api 调用正确设置。另请参阅在回调中调用 $rootScope.$apply() 以跨 Angular 应用程序同步对象。现在,每当我尝试在我的 Controller 中检索对象“Data.customerServerRowObject”时,我都会得到“undefined”值:

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

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

}

这是因为当 api 回调还没有完成时, Controller 内部的代码就被执行了。我也在做 $rootSope.$apply() 这对我的运行功能没有影响

最佳答案

你需要使用 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;
  });
}

关于javascript - $rootScope.$apply() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28437635/

相关文章:

javascript - Web Speech API 滞后时间——如何解决?

javascript - Nodemailer:ERR_CONNECTION_RESET 与 AngularJS 和 NodeJS 与 POST

javascript - 使用 JavaScript 替换 DIV 中的图像

用于匹配以给定模式开头的代码块的 Javascript 正则表达式

javascript - 是否有一种 JavaScript/css 方法可以使同步滚动区域类似于 "meld"?

javascript - 循环遍历表并将特定单元格存储在数组中(如果选中行)

xml - 使用用户输入数据在 angularjs 中生成 xml 并将其发送到 Web 服务

angularjs - AngularJS + Elasticsearch-如何搜索文档

javascript - AngularJS:带有查询字符串和表单的单页应用程序?

javascript - 在 AngularJS 中使用范围和 Controller 时发生冲突