简体   繁体   中英

Confused about $http interceptors in Angular js

Really can not find good documentation about http interceptors in Angular js. While handling errors coused by ng-include i can intercept responseError by using this:

    app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('templateInterceptor');
});

// register the interceptor as a service
app.factory('templateInterceptor', function($q) {
  return {
    'responseError': function(rejection) {
       var isTemplate = !!rejection.config.url.match(/^content/g);
       if (isTemplate) {
         // here we add error message, but how this message appesrs in the place of ng-include
         rejection.data = '<div><template-error url="\''+ (rejection.config.url) + '\'"><strong>Error from interceptor.</strong></template-error></div>';
         return rejection;
       } else {
         return $q.reject(rejection);
       }
    }
  }
});

This code was taken from this question how to catch angular ng-include error . I don't get, how interceptors works? What they must return? How to use rejection parameter that passed to the responseError interceptor? In rejection the data property is used to include error message into the place of failed ng-include directive, how this works?

If you have call to $http , such as

$http(....).then(function(results) {
  // Success callback
}, function(error) {
  // Error callback
});

And the server responds with an error, then the responseError interceptors will get invoked before running either the success or error callbacks.

  • If the final interceptor returns any value that is not a promise, then from the point of view of the calling code, the call to $http was successful, and the success callback will be executed, passing in the returned value as the results argument

  • If the final interceptor returns a promise that gets resolved with a value, then similar to the case above, from the point of view of the calling code, the call to $http was successful, and the success callback will be executed, passing in the resolved value as the results argument.

  • If the final interceptor returns a promise that is rejected with an error, then from the point of view of the calling code, the call to $http was not successful, and the error callback will be executed, passing in the rejected error as the error argument.

The ngInclude directive will inject into the page the data key from the results of a successful call to $http . The code at https://stackoverflow.com/a/20838764/1319998 transforms what would be an errored call to $http from ngInclude , into a success, with html of an error message as the data key in the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM