[英]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.