0

我正在学习 Angularjs,我正在尝试创建一个服务来执行需要为我的所有控制器完成的常见任务。

我目前收到错误:

TypeError: Cannot call method 'getAuthHeader' of undefined

应用程序.js

var token = "mytoken"
var baseUrl = "mybaseUrl";

var myezteam = angular.module('myezteam', ['ui.bootstrap']);

myapp.config(function($routeProvider) {
    $routeProvider
        .when('/profile', 
            {
                controller: 'ProfileController',
                templateUrl: 'template.html'
            })
        .otherwise({redirectTo: '/profile'});
});

// This gets the basic information that is needed for every page
myapp.service('base', function() {

    this.getAuthHeader = function($http) {
        // Set authorization token so we know the user has logged in.
        return $http.defaults.headers.common.Authorization = 'Bearer ' + token;
    }
});

profile.js

 myapp.controller('ProfileController', ['$scope', '$http', function($scope, $http, base) {

        base.getAuthHeader($http);  // <-- THIS LINE IS THROWING THE ERROR
    }]);

为什么会发生错误,我该如何解决?另外,有没有办法在我的应用程序上设置配置,这样我就不需要调用base.getAuthHeader($http);每个控制器,但是当每个控制器加载时它会自动被调用?

4

1 回答 1

2

您没有将服务base注入控制器。您需要以与$scope和相同的方式注入它$http

myapp.controller('ProfileController', ['$scope', '$http', 'base', 
    function($scope, $http, base) { ... });
于 2013-11-11T01:05:18.193 回答