Angular uses the Interceptor to uniformly process http requests and responses.

Source: Internet
Author: User

Angular uses the Interceptor to uniformly process http requests and responses.

If you want to use htpp in angularjs to send requests to the backend, a token that is uniquely identified by the user wants to be placed in headers, that is, {headres: {'Token': 1 }}

The following js is introduced in index.html:

angular.module('app.factorys',[])  .factory('httpInterceptor',['$q','$injector','$localStorage',function ($q,$injector,$localStorage) {    var httpInterceptor = {      'responseError' : function(response) {        // ......        return $q.reject(response);      },      'response' : function(response) {        if (response.status == 21000) {          // console.log('do something...');        }        return response || $q.when(response);      },      'request' : function(config) {        config.headers = config.headers || {};        if ($localStorage.token) {          config.headers.token = $localStorage.token;          // config.headers['X-Access-Token'] = $localStorage.token;        };        return config || $q.when(config);        return config;      },      'requestError' : function(config){        // ......        return $q.reject(config);      }    };    return httpInterceptor;  }])

After the factory is injected into the app, configure it in config

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

The above angular method of handling http requests and responses with the interceptor is all the content that I have shared with you. I hope you can give us a reference and hope you can provide more support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.