[英]Why can't I inject a service into Angular factory/injector?
我已经编写了用于调用Web API的身份验证服务(AuthenticationService)。 我最近了解了拦截器。 我想创建一个拦截器来拦截请求并根据AuthenticationService的状态修改标头。
将AuthenticationService注入到我的拦截器中时,我遇到了一些问题。 当我这样做时,我的页面坏了。 我看到诸如{{MyVariableName}}之类的东西,而不是值。 另外,提交表单无效。 单击按钮没有任何反应。
我不知道问题是什么,因为我找不到任何错误消息或任何指示问题的原因。 控制台中没有任何内容。 页面刚刚坏了。 如果我从拦截器中删除AuthenticationService,一切将再次起作用。 以下是我的拦截器代码:
app.factory('authInjector', ['AuthenticationService', function (AuthenticationService) {
var authInjector = {
request: function (config) {
config.headers['x-session-token'] = 'test';
return config;
}
};
return authInjector;
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('authInjector');
}]);
“ app”是在另一个JavaScript文件(app.js)中定义的。 这也是AuthenticationService所在的位置。 该服务的声明如下:
app.service('AuthenticationService', function ($http) { ... }
我的脚本按以下顺序加载:
<script src="~/Scripts/app.js"></script>
<script src="~/Scripts/injector.js"></script>
我还尝试在拦截器代码中使用$ injector,但这毫无用处。 我收到一条错误消息,指出$ injector在运行时未定义。
var AuthService = $injector.get('AuthenticationService');
谁能告诉我AuthenticationService的拦截器问题是什么?
谢谢
编辑:要求的信息:
<html ng-app="MyAppName">
app.js:
angular.module('MyAppName').controller('LoginController', function ($scope, $rootScope, $window, AuthenticationService) {
var app = angular.module('MyAppName', ['ngRoute', 'ngSanitize', 'ngMaterial', 'ngMessages', 'material.svgAssetsCache']);
控制台中没有错误。
在您的authInjector中尝试一下 :
var AuthenticationService = $injector.get('AuthenticationService');
改变:
app.factory('authInjector', ['AuthenticationService', function (AuthenticationService) {
至:
app.factory('authInjector', ['$injector', function ($injector) {
脚本顺序:
<script src="~/app/app.js"></script> // create the app and dependencies
<script src="~/app/authentication.service.js"></script> // create the authentication service
<script src="~/app/auth-injector.service.js"></script> // create the interceptor factory
<script src="~/app/app.config.js"></script> //push the interceptor to httpProvider
看起来您的拦截器中有circular dependency
。 您尝试注入使用$http
的服务,同时尝试配置$httpProvider
。
一种解决方案是将authService
手动注入到拦截器的request
属性中。
app.factory('authInjector', ['$injector', function($injector) {
var authInjector = {
request: function (config) {
var AuthService = $injector.get('AuthService');
// Do whatever you need to do with AuthService
config.headers['x-session-token'] = 'test';
return config;
}
};
return authInjector;
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.