2016-06-28 150 views
1

我有一個簡單的角度攔截器攔截請求並添加授權標頭。它還攔截響應錯誤401以知道請求是否因授權失敗。

不幸的是它似乎與$資源混亂,因爲我的$資源調用始終返回成功回調,並從來沒有一個錯誤(無論是400或500)。

它確實是攔截器,因爲如果我刪除它,$ resource調用將返回正確的回調。

有關如何解決此行爲的任何想法?

這裏的攔截請求:

function request(config) { 
    var token = 'whatever-my-token-is'; 

    if (token) { 
     config.headers.authorization = token; 
    } 

    return config; 
    } 

而且responseError:

function responseError(response) { 
    if (response.status === 401) { 
    $rootScope.$broadcast('unauthorized'); 
    } 

    return response; 
} 

任何幫助表示讚賞

回答

0

我認爲你需要使用一個承諾返回錯誤。
$q加入您的Interceptor工廠。 像這樣

$provide.factory('MyHttpInterceptor', function ($q){ 
    ... 
}) 

,然後讓responseError()

function responseError(response) { 
    if (response.status === 401) { 
    $rootScope.$broadcast('unauthorized'); 
    } 

return $q.reject(response); 
} 

這個環節也可能有助於https://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/

+0

這解決了問題,非常簡單,非常感謝! – QuantumDream