Angular.js中的2个控制器之间存在竞争条件问题,带有Ajax和localStorage值
Issue with race condition betwen 2 Controllers in Angular.js with Ajax and a localStorage value
myIdentity的值只创建一次,并且在首次使用以下Angular.js控制器后,会永久保存在本地存储中。
函数$scope.createIdentity((是全局控制器中的一个复杂函数,它将结果保存到$localstorage.myIdentity。这非常有效!!!createIdentity((函数在其内部使用Q promise。但在AppCtrl中,我遇到了竞争条件的问题,因为$localstorage.myIdentity以前尚未解决我的$http XHR请求被激发。所以它不包含myId的任何值。
这种情况仅在第一次使用控制器时发生。
但我需要在第一次调用AppCtrl时启动socket.io连接,这对我来说是一个更大的问题
第二次使用AppCtrl时,$localStorage中还提供了myIdentity的正确值。
TimeacleControllers.controller('StatusCtrl', ['$scope', '$http', 'Socket', '$localStorage',
function ($scope, $http, Socket, $localStorage) {
if ($localStorage.myIdentity === undefined) {
$scope.createIdentity();
}
var myParams = {
myId: $localStorage.myIdentity
};
$http
.post('http://example.org', myParams)
.success(function (data) {
console.log('received data: ' + data);
Socket.connect();
Socket.on('connected', function () {
console.log("Connection!");
});
Socket.on('message', function (msg) {
console.log("Message: " + msg);
});
})
.error(function (err) {
// Handle login errors here
console.log("Error - " + err);
});
}]);
那么,您可以在这里做些什么来让Ajax请求等待$localstorage.myIdentity得到解决呢?请帮忙。
您提到了Q promise,但异步序列有问题。。。?
如果createIdentity
返回promise,只需将http调用放入.then
中即可
$scope.createIdentity().then(function() {
$http.... // or you can wrap it inside a function
})
编辑:如果您无法访问填充变量的代码(通常发生在指令内部(,您可以设置一个一次性监视来监视值的变化。
var unwatch = $scope.$watch(function(){
return $localStorage.myIdentity;
}, function(newValue){
if (newValue === undefined) return;
$http...
unwatch();
});
您说过$scope.createIdentity()
使用promise(可能是异步操作(。让它返回一个让代码遵守的承诺。当它解析时,让它解析身份。
承诺是可链接的。当您从then
返回一个promise时,下一个then
将侦听该promise而不是原始promise。在这种情况下,我们让下一个then
监听AJAX。
$scope.createIdentity().then(function(identity){
// When createIdentity resolves, use the data for the AJAX.
// Return the AJAX promise for the next chained then.
return $http.get(...);
}).then(function(data){
// When the AJAX completes, use the data for the socket call
Socket.connect();
...
});
- 带有slideUp/Down和clearQueue的jQuery问题
- 带有 JavaScript 随机数函数的未知问题
- 带有.css()串联问题的jQuery变量
- 访问带有变量的Object元素时出现问题
- 带有jquery验证问题的php表单
- 带有附录的撇号问题
- 带有两个提交按钮的提交表单,每个按钮执行不同的操作问题
- 我正试图获得一个带有复选框的多选下拉列表,在填充项目和获得所有选中的工作时遇到了一些问题
- 在 UIWebview 中加载带有帖子的 URL 时出现问题
- 防止'单击'多次触发的事件+带有衰落的问题
- 问题将 Javascript 数组发送到带有 List
参数的 Web API 方法 - 带有页面导航问题的 HTML5 滑块
- 带有 mvc 部分视图问题的花哨框
- Ionic:带有选项卡和侧菜单导航问题的主详细信息
- 将参数传递给带有“myarguments.”的函数时出现问题.'在咖啡脚本中
- 带有日语文本的安卓 2.3 键盘问题
- 带有JavaScript内容的iframe.双击问题
- 反应中带有回调函数的问题
- 带有反斜杠的 Javascript 字符串比较问题
- IE上带有滚动条渲染问题的可手动固定标题