处理Angularjs中的$ http.get和$ http.post错误

run*_*ero 2 post get http angularjs

伙计们,

我使用$http.get$http.post所有在我的代码.对于如何处理这些呼叫在全球范围内发生的错误,我有点迷茫.目前我.success(doSomething).error(doSomething)每次通话都有.

我想更改此内容,而只是在页面顶部显示错误.

我读到了使用拦截器myapp.something.但我绝对不明白如何实现这一点.

请帮助

Cla*_*Pan 6

响应拦截器在angularjs应用程序的配置阶段附加.您可以使用它们全局响应任何$ http请求.请注意,模板文件也使用$ http请求,因此您可能希望将拦截器中的某些请求仅过滤到您希望响应的请求.

成功使用响应拦截器需要很好地理解promises模式.

下面是一个如何使用它们的例子:

angular.module('services')
    .config(function($httpProvider){
        //Here we're adding our interceptor.
        $httpProvider.responseInterceptors.push('globalInterceptor');
    })
    //Here we define our interceptor
    .factory('globalInterceptor', function($q){
        //When the interceptor runs, it is passed a promise object
        return function(promise){

            //In an interceptor, we return another promise created by the .then function.
            return promise.then(function(response){
                //Do your code here if the response was successful

                //Always be sure to return a response for your application code to react to as well
                return response;
            }, function(response){
                //Do your error handling code here if the response was unsuccessful

                //Be sure to return a reject if you cannot recover from the error somehow.
                //This way, the consumer of the $http request will know its an error as well
                return $q.reject(response);
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 注意!!此方法已被弃用.请点击此链接获取替代方案http://docs.angularjs.org/api/ng.$http (6认同)