如何使用AngularJS覆盖头标记

如何使用AngularJS覆盖头标记,angularjs,Angularjs,我无法用AngularJS覆盖头标记,因为已使用AuthInterceptor设置了头标记 app.factory('authInterceptor', function ($rootScope, $q, $window) { return { request: function (config) { config.headers = config.headers || {}; if (localStorage.getItem("token")!=='') { c

我无法用AngularJS覆盖头标记,因为已使用
AuthInterceptor
设置了头标记

app.factory('authInterceptor', function ($rootScope, $q, $window) {
 return {
   request: function (config) {

   config.headers = config.headers || {};
   if (localStorage.getItem("token")!=='') {
     config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
   }
   return config;
 },
};
});

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

我将访问另一个第三方URL,其中使用了另一个令牌,但总是失败,因为令牌返回到
localStorage
中的当前令牌。我使用了
TransformRequest
,但也不起作用,解决此问题的最佳做法是什么?

您可以检查截获请求中的URL是否是要传递授权令牌的URL。例如,如果您自己的API的URL总是以
https://api.myapp.com
,您可以这样做:

app.factory('authInterceptor', function ($rootScope, $q, $window) {

    var urlForAuthorization = 'https://api.myapp.com';

    return {
        request: function (config) {
            config.headers = config.headers || {};

            if (config.url.startsWith(urlForAuthorization) 
                && localStorage.getItem("token") !== '') {
                config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
            }

            return config;
        }
    };
});

您可以将$http拦截器更改为仅为本地url设置授权令牌。谢谢@nikolajdallarsen您能给出示例代码吗?