我在尝试在工厂中使用服务时遇到未知的提供程序错误。当我将工厂推入拦截器时,控制台会记录错误:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- authService <- authInterceptor <- $http <- $templateRequest <- $compile
我认为authService还没有准备好,但我不清楚如何创建它以便它。你能解释在工厂中使用authService的正确方法吗?
app.js
angular.module('app', [
'ngResource',
'ngRoute',
'ui.calendar',
'calendarControllers',
'accountControllers',
'commonControllers',
'commonServices'
]).
constant('API', 'http://127.0.0.1:8000').
config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/cal.html',
controller: 'CalCtrl'
})
.when('/account', {
templateUrl: '/account.html',
controller: 'AccountCtrl'
})
.otherwise({
templateUrl: '/login.html'
});
}
]);
services.js
'use strict';
angular.module('commonServices', []).
factory('authInterceptor', ['API','authService',
function (API, auth) {
return {
request: function(config) {
var token = auth.getToken();
if(config.url.indexOf(API) === 0 && token) {
config.headers.Authorization = 'JWT ' + token;
}
return config;
},
// If a token was sent back, save it
response: function(res) {
if(res.config.url.indexOf(API) === 0 && res.data.token) {
auth.saveToken(res.data.token);
}
return res;
}
}
}
]).
config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}).
service('authService', ['$scope', '$window',
function ($scope, $window) {
$scope.saveToken = function(token) {
$window.localStorage['jwtToken'] = token;
};
$scope.getToken = function() {
return $window.localStorage['jwtToken'];
};
$scope.logout = function() {
$window.localStorage.removeItem('jwtToken');
};
}
]);
答案 0 :(得分:0)
您无法访问服务内部的$scope
,这就是您的服务初始化已停止,以及应用程序抛出$scope
提供程序数组的原因。
service('authService', ['$window', function($window){
//..code here..
}])