如何从AngularJS中的服务调用工厂

时间:2013-10-15 19:41:48

标签: javascript angularjs

我有一个使用Yeoman设置的AngularJS应用程序。在应用中,我需要进行HTTP Basic Authentication后面的API调用。我跟着this tutorial找出了如何修改我的HTTP标头并对uername和密码进行编码。但是,我无法弄清楚如何从我的API服务中调用Base64.encode。我尝试过的所有内容都会给我ReferenceError: Base64 is not defined错误。

我的API服务,Base64.encode()是引发错误的行:

// 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工厂:

// 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>

1 个答案:

答案 0 :(得分:4)

在这一行

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

您需要注入Base64服务 - 即

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