2017-03-03 85 views
2

我想在Angular JS端實現一個攔截器,爲此我將檢查特定的響應並將用戶導航到其他頁面。這是我的攔截Angular JS攔截器檢查響應數據返回html

App.factory('InterceptorService',['$q', '$location', function($q, $location, $http){ 
var InterceptorServiceFactory = {}; 

var _request = function(config){ 
    console.log('Coming inside'); 
    console.log(config); 
    return config; 
} 

var _response = function(response){ 
    console.log('Coming inside for Result'); 
    console.log(response); 
    if (response.data.code == "USER_TIMEDOUT") { 
     window.location.href = '/unrestricted/jsp/FormLogin.jsp'; 
     alert(worked); 
    } 
    return response; 
} 

InterceptorServiceFactory.request = _request; 
InterceptorServiceFactory.response = _response; 
return InterceptorServiceFactory; 
}]); 

App.config(["$httpProvider", function ($httpProvider) { 
$httpProvider.interceptors.push('InterceptorService'); 
}]); 

這是春天攔截我的API響應

{ 
"code": "USER_TIMEDOUT", 
"message": "User session timedout for requestUri=/services/search/Employee" 
} 

我想檢查我的反應和檢查代碼,如果代碼相匹配,我試圖把oput他到另一個屏幕。但是每當我在控制檯內部看到數據中的響應時,就會看到Html。

當我分析網絡選項卡時,我能夠看到API調用失敗,響應401。而所有其他HTML已加載,而加載的HTML。響應數據進入Html。所以我在Interceptor中缺少的東西?

回答

3

由於響應代碼401(超過400被認爲是一個請求失敗), 你需要使用

InterceptorServiceFactory.responseError = _response; 

this answer看一看了解更多詳情