我在将我的 $http 拦截器和我的应用程序配置分隔在单独的文件中时遇到问题。这是我尝试过的:
应用程序.js
angular
.module('myApp', [
'oc.lazyLoad',
'ui.router',
'ui.bootstrap',
'angular-loading-bar',
])
.config(['$stateProvider', '$urlRouterProvider', '$ocLazyLoadProvider', function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
debug: false,
events: true,
});
$urlRouterProvider.otherwise('/page/home');
$stateProvider
.state('page', {
url: '/page',
templateUrl: '../views/pages/main.html',
resolve: {
loadMyDirectives: function ($ocLazyLoad) {
return $ocLazyLoad.load(
{
name: 'myApp',
files: [
'scripts/directives/header/header.js',
'scripts/directives/header/header-notification/header-notification.js',
'scripts/directives/sidebar/sidebar.js',
'scripts/directives/sidebar/sidebar-search/sidebar-search.js'
]
})
,
$ocLazyLoad.load(
{
name: 'ngResource',
files: ['bower_components/angular-resource/angular-resource.js']
}),
$ocLazyLoad.load(
{
name: 'angular-storage',
files: ['bower_components/a0-angular-storage/dist/angular-storage.min.js']
}) ,
$ocLazyLoad.load(
{
name: 'sjcl',
files: ['bower_components/sjcl/sjcl.js']
})
}
}
})
.state('page.home', {
url: '/home',
controller: 'MainCtrl',
templateUrl: '../views/pages/home.html',
resolve: {
loadMyFiles: function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'myApp',
files: [
'scripts/controllers/main.js'
]
})
}
}
})
.state('login', {
templateUrl: 'views/pages/login.html',
url: '/login',
resolve: {
loadMyFile: function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'myApp',
files: [
'bower_components/a0-angular-storage/dist/angular-storage.min.js',
'scripts/service/userService.js',
'scripts/service/authService.js'
]
}),
$ocLazyLoad.load(
{
name: 'sjcl',
files: ['bower_components/sjcl/sjcl.js']
}),
$ocLazyLoad.load(
{
name: 'myApp',
files: ['scripts/controllers/login/login.js']
})
}
}
})
.state('page.addMoneyFlow', {
templateUrl: 'views/pages/add.html',
url: '/addMoneyFlow'
})
.state('page.reports', {
templateUrl: 'views/pages/reports.html',
url: '/reports'
})
}])
authService.js
angular.module('myApp')
.service('AuthInterceptor', function($rootScope) {
var service = this;
service.request = function(config) {
alert('test')
//config.headers.authorization = "sdjkghsdlfkjghfldkjghsfdkljghdslkjghsdfkjghsdflkjghk";
return config;
};
service.responseError = function(response) {
if (response.status === 401) {
$rootScope.$broadcast('unauthorized');
}
return response;
};
}).config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
}])
登录.js
angular.module('myApp')
.controller('LoginController', function ($scope, $http, UserService) {
var login = $scope;
login.email = "";
login.password = "";
login.login = function () {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {
$scope.names = response.records;
});
};
})
如果我将 authService.js 的代码直接放在 app.js 源代码下,一切都很好,但如果我把它放在一个单独的文件中,我不会收到错误,但拦截器不起作用。
有人能帮忙吗?