Search code examples
angularjsangularjs-scopeangularjs-serviceangularjs-factory

Unable to set the http defaults inside the angularjs factory


In my Angularjs application, I have a factory and I need to authenticate a user. I am using the httpProvider to set the defaults. But I am getting the error stating $httpProvider is not defined.

'use strict';
 angular.module('myApp')
.factory('authService', function ($q, $http, $rootScope, $window) {
    return {
        authenticateUser: function () {
           ........
           ........
       $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
       $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

I then tried by adding the $httpProvider in the factory dependency

'use strict';
 angular.module('myApp')
.factory('authService', function ($q, $http, $rootScope, $window, httpProvider ) {
    return {
        authenticateUser: function () {
           ........
           ........
       $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
       $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

This time I am getting the Unknown provider: $httpProviderProvider <- $httpProvider <- authService

Please let me know where I am going wrong.


Solution

  • You can't get service provider inside the factory.

    You can use interceptors to add a default value to each http request.

    angular.module('myApp').config(function ($httpProvider) {
        $httpProvider.interceptors.push('authInterceptorService');
    });
    
    angular.module('myApp').factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
    var authInterceptorServiceFactory = {};
    var _authentication = {
        isAuth: false,
        userName: ""
    };
    
    var _request = function (config) {
        config.headers = config.headers || {};
        var authData = localStorageService.get('data');
        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData;
        }
    
        return config;
    }
    
    authInterceptorServiceFactory.request = _request;
    
    return authInterceptorServiceFactory;
    }]);