lightswitch05
lightswitch05

Reputation: 9428

How to call a factory from a service in AngularJS

I have an AngularJS app I setup using Yeoman. In the app, I need to make an API call that is behind HTTP Basic Authentication. I followed this tutorial to figure out how to modify my HTTP headers and encode the uername and password. However, I cannot figure out how to call Base64.encode from my API service. Everything I've tried keeps giving me ReferenceError: Base64 is not defined errors.

My API Service, Base64.encode() is the line that throws the error:

// app/scripts/api.js
angular.module('api.ClientApp', ['base64']).
    service('$api', function($http, $q, $cookieStore, $rootScope, $location, $window, $sniffer) {
        var $api = this;

        this.set_http_auth = function(obj) {
            if(obj){
                $http.defaults.headers.common['Authorization'] = 'Basic ' +
                    Base64.encode(obj.username + ':' + obj.password);
            } else {
                delete $http.defaults.headers.common['Authorization'];
            }
        };
    });

Base64 Factory:

// app/scripts/services/Base64.js
angular.module('base64', [])
    .factory('Base64', function () {
        return {
            encode: function (input) {
                var output = "";
                // ...
                return output;
            },

            decode: function (input) {
                var output = "";
                // ...
                return output;
            }
        };
    });

Index.html:

<!-- app/index.html -->
<script src="scripts/app.js"></script>
<script src="scripts/services/Base64.js"></script>
<script src="scripts/api.js"></script>
<script src="scripts/controllers/signin.js"></script>

Upvotes: 0

Views: 2094

Answers (1)

Andyrooger
Andyrooger

Reputation: 6746

In this line

service('$api', function($http, $q, $cookieStore, $rootScope, $location, $window, $sniffer) {

you need to inject the Base64 service - i.e.

service('$api', function($http, $q, $cookieStore, $rootScope, $location, $window, $sniffer, Base64) {

Upvotes: 4

Related Questions