【发布时间】:2014-07-12 00:03:12
【问题描述】:
所以这很奇怪。 $rootScope 在函数中正确设置,但随后失去其价值。如果我使用承诺,我只能保持价值。 (!?)
我正在使用 trigger.io (Forge) AJAX 请求,成功后我更新$rootScope.queries。在成功块内,$rootScope.queries 设置正确,如alert 所示。
.run(function($rootScope, $state, $q) {
var retrieveHistory = function() {
forge.logging.log("Retrieving history");
// Retrieve the history
forge.request.ajax({
type: 'GET',
url: 'http://localhost:9000/json',
dataType: 'json',
success: function (data) {
$rootScope.queries = data["queries"];
alert("queries " + JSON.stringify($rootScope.queries));
},
error: function (error) {
}
});
}
retrieveHistory();
此时,在调用 retrieveHistory() 之后,$rootScope.queries 现在为空。视图没有更新,使用 Chrome 控制台检查显示它是空的。
假设我向函数添加了一个承诺,但实际上并没有将承诺用于任何事情。
.run(function($rootScope, $state, $q) {
var retrieveHistory = function() {
var deferred = $q.defer();
forge.logging.log("Retrieving history");
// Retrieve the history
forge.request.ajax({
type: 'GET',
url: 'http://localhost:9000/json',
dataType: 'json',
success: function (data) {
$rootScope.queries = data["queries"];
alert("queries " + JSON.stringify($rootScope.queries));
},
error: function (error) {
deferred.reject("error " + JSON.stringify(error));
}
});
return deferred.promise;
}
var promise = retrieveHistory();
promise.then();
有了这个承诺,$rootScope.queries 将保持其价值。视图更新,Chrome 检查器显示该值设置正确。
这是为什么?我根本不理解这种行为。为什么我不能在原始代码中保留$rootScope.queries 的值?为什么 promise 会保值?
【问题讨论】:
标签: angularjs angularjs-scope promise trigger.io angular-promise