2016-06-01 18 views
2

404反應在我的web應用程序我到遠程HTTP的WebAPI服務執行GET命令

$http.get(url).then(function(data) { do_something(); }); 

一切正常時的WebAPI返回一些數據,但是,當WebAPI返回404錯誤(不顯示數據)時,該函數似乎不會觸發。 如何爲其設置回調?

回答

4
$http.get(url).then(function(data) { 
    do_something(); 
}, function(err) { 
    // your error function 
    if (err.status == 404) { 
    do_something_else(); 
    } 
}); 
2

我認爲對於404響應,最好的辦法是顯示正確的未找到頁面。在angularjs中,您可以使用$ injector服務攔截響應。所以你可以創建一個服務,查找404響應並顯示404頁面。

angular.module('mymodule') 

    .service('APIInterceptor', function($injector) { 
     return { 
     'request': function(config){ 
      // request logic goes here. 
     }, 
     'responseError' : function(response){ 
      if (response.status === 404) { 
      $injector.get('$state').go('error_500'); 
      } 
     return response; 
     } 
    }; 
    }); 
1

$http返回狀態碼作爲第二個參數。

$http.get(url) 
    .success(function(data, status) { 
     alert(status); 
    }) 
    .error(function(data, status) { 
     alert('Error with status code: ' + status); 
    }); 

status - {number} - HTTP響應的狀態代碼。

但是,如果狀態是錯誤狀態,例如404,那麼錯誤塊將被稱爲