我正在学习Angularjs,我正在尝试创建一项服务,以完成需要为所有控制器完成的常见任务。
我目前收到错误:
TypeError: Cannot call method 'getAuthHeader' of undefined
app.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);
,但是当每个控制器加载时它会自动被调用?
答案 0 :(得分:2)
您没有将服务base
注入控制器。您需要以与$scope
和$http
myapp.controller('ProfileController', ['$scope', '$http', 'base',
function($scope, $http, base) { ... });