2016-09-29 62 views
0

我有一个$http服务来进行API调用,并且我有一个transformResponse和错误拦截器都附加到每个调用。如果出现错误,我可以看到转换响应首先被调用,然后是拦截器。我不希望为错误响应调用转换方法,我希望它跳过拦截器。我怎样才能做到这一点?

我知道我可以把(response.status != 200)放到每个转换方法中,但我有很多这些方法,我不想在它们中的每一个中都这样做。

+0

去与任何自定义商 –

回答

2

你可能需要去拦截器玩一般的请求响应。

myApp.factory('authInterceptor', function ($rootScope, $q, $window) { 
    return { 
    request: function (config) { 
     config.headers = config.headers || {}; 
     if ($window.sessionStorage.token) { 
     config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token; 
     } 
     return config; 
    }, 
    response: function (response) { 
     if (response.status === 401) { 
     // handle the case where the user is not authenticated 
     } 
     return response || $q.when(response); 
    } 
    }; 
}); 

myApp.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('authInterceptor'); 
}); 
0

也许这也将是有益的

app.config(['$httpProvider', function ($httpProvider) { 
    $httpProvider.defaults.transformResponse.unshift(
     function (data, headers) { 
      /* some code*/ 
      return data; 
     }); 
}])