[英]Setting up a listener with $watch in Angular JS
我有一项服务,可以异步两次连续调用API。
我希望该应用程序在继续进行之前都等待解决,并且由于调用之一可能会也可能不会发生,因此我相信$watch
是解决嵌套或链接回调的方法。
var response_complete = {call1:false, call2:false};
$http.post("myapi.com/slug", data, header).then(function(res){
/* ... */
response_complete.call1 = true;
});
if(make_this_call==true){
$http.post("myapi.com/anotherslug", data, header).then(function(res){
/*...*/
response_complete.call2 = true;
});
} else response_complete.call2 = true;
$scope.$watch("response_complete",function(){
if(response_complete.call1==true && response_complete.call2==true){
console.log("DONE!");
}
});
因此,其想法是创建一个全局变量,并在两个调用完成时对其进行监视。 如果没有进行第二个调用(是有条件的),则立即将其响应变量设置为true
。
但是$watch
回调仅被触发一次,并且其中的条件(call1&call2 == true)永远不会被满足。
您的手表不起作用,因为响应完成不是$scope
变量| 属性:
// replace this with $scope property declaration
//var response_complete = {call1:false, call2:false};
$scope.response_complete = {call1:false, call2:false};
然后在随后的代码中使用$scope.response_complete
修改其值,因此$watch
将在$scope.response_complete
更改时被触发。
更好的解决方案:
正如其他人指定的那样,使用$broadcast
比使用$broadcast
$watch
更好,因此,代替观看变量throw事件并在$scope
捕获这些事件。
$http.post("myapi.com/slug", data, header).then(function() {
// stuff
$scope.$broadcast("POST_SLUG_COMPLETE");
});
$http.post("myapi.com/anotherslug", data, header).then(function() {
// stuff
$scope.$broadcast("POST_ANOTHERSLUG_COMPLETE");
});
// then in your $scope
$scope.$on("POST_SLUG_COMPLETE", function () {
// stuff
});
$scope.$on("POST_ANOTHERSLUG_COMPLETE", function () {
// stuff
});
希望能有所帮助
如果您需要当前范围的“全局”变量,则可以执行以下操作:
$scope.complete = false;
$http.post("myapi.com/slug", data, header).then(function(res) {
$http.post("myapi.com/anotherslug", data, header).then(function(res) {
$scope.complete = true;
console.log("DONE!");
});
});
您也可以使用$ rootScope获得更“全局”的值。 其他替代方法是$ broadcast或服务中的资产。
但更重要的是确保您如何使用异步调用。 如果您想解决两个问题,请将第二个电话放在第一个电话内。 您提供的示例无效,因为response_complete.call1 = true在异步线程中,并且在您尝试验证时始终为false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.