我正在尝试在Angular 1.4.x中创建一个简单的HTTP拦截器(使用ES6和Babel)。如果检测到HTTP 500,它唯一需要做的是重定向到错误页面。代码:
应用/中间件/ securityInterceptor.service.js
export default class SecurityInterceptorService {
constructor($q, $location, config) {
'ngInject';
this.$location = $location;
this.config = config;
this.$q = $q;
}
responseError(rejection) {
var deferred = this.$q.defer();
if (rejection.status === 500) {
this.$location.path(this.config.errorPagePath);
}
deferred.reject(rejection);
return deferred.promise;
}
}
现在,我在尝试运行应用程序时收到一个未知的提供程序错误,指出SecurityInterceptorService
未知。所以我看看它是如何注册的。但是,我没有看到任何明显的错误:
index.module.js
import interceptorConfig from './index.interceptors';
import SecurityInterceptorService from '../app/middleware/securityInterceptor.service';
// other imports
angular.module('app', ['ngTouch' /*, other dependencies */])
.config(interceptorConfig)
.service('securityInterceptorService', SecurityInterceptorService)
// other declarations
index.interceptors.js
export default function interceptorConfig($httpProvider, securityInterceptorService) {
'ngInject';
// Security interceptor
$httpProvider.interceptors.push(securityInterceptorService);
}
删除interceptorConfig
依赖项时,我可以输入securityInterceptorService
函数。所以似乎服务没有注册。检查所有文件路径,检查变量名称中的拼写错误等等。
如果有人能够指出我犯的错误,我会很感激。
------------------------更新
但是,通过.config()
注入的以下功能确实有效。然而,当我尝试在此函数中推送securityInterceptor时,我得到了相同的未知提供程序错误。
export default function config($logProvider, $locationProvider, toastr, $compileProvider) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
// Set options third-party lib
toastr.options.timeOut = 3000;
toastr.options.positionClass = 'toast-top-right';
toastr.options.preventDuplicates = true;
toastr.options.progressBar = true;
// HTML 5 Modus Enabled No #
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
hashPrefix: '!'
});
// Disable debug info
$compileProvider.debugInfoEnabled(true);
}
答案 0 :(得分:1)
在.config()
中输出无法注入服务的数据。将index.interceptors.js
更改为此内容时,一切正常:
export default function interceptorConfig($httpProvider) {
'ngInject';
// Security interceptor
$httpProvider.interceptors.push('securityInterceptorService');
}