user2352879
user2352879

Reputation: 159

AngularJS cannot find provider

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');
      };
    }
]);

Upvotes: 2

Views: 528

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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..
}])

Upvotes: 1

Related Questions