2012-07-22 123 views
28

有誰知道如何檢查資源是否無法在AngularJS中獲取?AngularJS失敗的資源GET

例如:

//this is valid syntax 
$scope.word = Word.get({ id : $routeParams.id },function() { 
    //this is valid, but won't be fired if the HTTP response is 404 or any other http-error code 
}); 

//this is something along the lines of what I want to have 
//(NOTE THAT THIS IS INVALID AND DOESN'T EXIST) 
$scope.word = Word.get({ id : $routeParams.id },{ 
    success : function() { 
     //good 
    }, 
    failure : function() { 
     //404 or bad 
    } 
}); 

任何想法?

回答

48

當您的第一個回調函數在發生錯誤時應該觸發一個額外的回調函數。從docs和組post採取:

$scope.word = Word.get({ id : $routeParams.id }, function() { 
    //good code 
}, function(response) { 
    //404 or bad 
    if(response.status === 404) { 
    } 
}); 
  • HTTP GET 「類」 動作:Resource.action([參數],[成功],[錯誤])
  • 非GET「類「動作:Resource.action([參數],postData,[成功],[錯誤])
  • 非GET實例操作:instance。$ action([parameters],[success],[error])
+0

完善。這正是我需要的。謝謝:) – matsko 2012-07-23 17:37:56

+1

問題出在if語句中。我需要寫if(reponse.status == 404),if(reponse.status == 500),if(reponse.status == 501),if .. if .. if?這不是代碼複製 – Adelin 2012-12-04 09:14:27

+1

@Adio您可以使用switch語句。 – 2013-02-09 01:50:01

5

也只是回答@Adio的問題。

當AngularJS認爲任何http響應代碼是錯誤時(只有[200,300]中的響應代碼被視爲成功代碼),將調用第二個回調函數。所以你可以有一個通用的錯誤處理函數,並不關心具體的錯誤。 根據錯誤代碼,if語句可用於執行不同的操作,但它不是強制性的。

0

這只是告知。

從角度1.6.x開始,不建議使用成功和失敗。所以現在請遵循當時的觀點,代表成功與失敗。

所以,上面的代碼看起來像在角1.6.x的是如下:

$scope.word = Word.get({ id : $routeParams.id }).then(=>() { 
    //this is valid, but won't be fired if the HTTP response is 404 or any other http-error code 
}).catch(=>() { 
    // error related code goes here 
}); 
+1

是的,但請注意,Angular團隊的「棄用」意味着「完全刪除」。還要注意,沒有失敗處理程序的$ resource將導致在「reason」中沒有有用的信息調用catch(reason)(空字符串,空數據,沒有其他字段)。您最好的/唯一的選項是使用get()。 $ promise.then(success(),fail()),並確保你處理失敗的func。還有祝你好運。 (V1.6.2) – tekHedd 2017-02-23 01:17:16