2

I'm getting an unknown provider error trying to use a service in a factory. When I push the factory into the interceptor, the console logs the error:

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- authService <- authInterceptor <- $http <- $templateRequest <- $compile

I'm thinking that authService is not ready yet but it's not clear to me how to create it so that it is. Can you explain the correct way to use the authService in the factory?

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');
      };
    }
]);
1
  • 1
    you cant inject $scope in to a service Commented Jun 28, 2015 at 16:46

1 Answer 1

1

You could not access $scope inside service, that is why your service initialization has been stopped, and app thrown $scope provider array.

service('authService', ['$window', function($window){
    //..code here..
}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.