我在 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/