簡體   English   中英

我可以在Angular JS promise api中使用jQuery.ajax嗎?

[英]Can I use jQuery.ajax with Angular JS promise api?

我在角度服務中有一個ajax函數,它根據后端服務檢查用戶的憑據。 我已經簡化了這個電話了。 當我使用$ http服務發出AJAX請求時,promise API可以正常工作:

function isOnline(){
    return $http.get(constants.dataUrl)
           .success(function(){return})
           .error(function(){return;});
}
function checkCredentials(){
    var online = isOnline();
    var checkCreds = online.then(function(){
        alert("Get succeeded");
    },
    function(response){
        alert("Get did not succeed");
    });
    return checkCreds;
}  

我看到當時定義的函數調用了。 當我使用jQuery ajax方法時,解析和延遲方法似乎沒有傳播並在online.then中觸發正確的方法。 以下代碼不起作用:

function isOnline(){
    var defer = $q.defer();

    $.ajax({
      url: constants.dataUrl,
      dataType: 'json',
      beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', basicAuthenticationToken());
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert("I am not online");
        defer.reject("I am not online");
      },
      success: function (data) {
        alert("I am online");
        defer.resolve(data);
      }
    });

    return defer.promise;
}
function checkCredentials(){
    var online = isOnline();
    var checkCreds = online.then(function(){
        alert("Get succeeded");
    },
    function(response){
        alert("Get did not succeed");
    });
    return checkCreds;
} 

我可以不使用promise API和普通的jQuery ajax方法嗎? 我想替換這些調用的原因與一個復雜的PhoneGap場景有關,它似乎不適用於Angular $ http。

Angularjs需要被告知其外部發生的變化。 由於ajax事件由jquery處理,因此您需要進行應用。 取決於函數的位置(可能是$ scope或$ rootScope)

defer.reject("I am not online");
$scope.$apply();

....
defer.resolve(data);
$scope.$apply();

這將讓角知道重新處理自己。 以下是關於它的文檔: http//docs.angularjs.org/api/ng.$ro​​otScope.Scope#$apply

您可以在任何時候使用此功能,只需要在角度以外編寫javascript,但需要將其連接到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM