Reputation: 4732
Here's a simple example of what i'm trying to do. I'll preface this by saying that i have been working as a maintainer for 3 weeks on an already built project in angular, and i have a minor, at best understanding of angular to date. i can work with the controllers and views and models, all that is fine. but when it comes time to understanding the dependency injection, i am stymied by vague errors. Now it's came time i need to learn about how the Injector works, so here's a small test app i have constructed for my own learning purposes. i do not actually know if this is the correct way to build an angular app at all. The documentation i find confusing at best.
html
<div ng-app="app">
<div ng-controller="EC as e">
</div>
</div>
javascript
var app = angular.module('app',[]);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q, $window) {
return {
'request': function(config) {
config.headers['Authorization'] = 'bearer '+ $window.localStorage.token;
return config;
}
};
});
}]);
function EC($scope,$http,$window) {
var vm = this;
vm.api = function( resource ){
return ('https://api.website.com/v1/'+resource).replace('//','/');
};
$window.localStorage.token = 'foobar';
$http.put( vm.api('/users/me'), { loggedIn: true }).then(function(response){
$http.get( vm.api('/users/me') ).then.function(response){
vm.user = response.data;
});
});
}
EC.$inject = ['$scope','$http','$window'];
app.controller('EC',EC);
app.run();
I had assumed the line EC.$inject = ['$scope','$http','$window'];
would insure that my controllers constructor would be called with those services, or whatever the hell they are called, as arguments. Apparently thats not the case. Can someone explain to me like i'm 5 how this works, and why i'm getting an error?
Error message:
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr
Upvotes: 0
Views: 258
Reputation: 2199
Rewrote the controller block to follow more conventionaly injection. Might workout for ya. Also removed the double response callback from the $http calls and returned the $http.get() promise.
angular.module('app', [])
.config(['$httpProvider', function($httpProvider)
{
$httpProvider.interceptors.push(function($window)
{
return {
request: function(config)
{
config.headers['Authorization'] = 'bearer '+ $window.localStorage.token;
return config;
}
};
});
}])
.controller('EC', ['$scope', '$http', '$window', function($scope, $http, $window)
{
var buildApiString = function(resource)
{
return ('https://api.website.com/v1/'+resource).replace('//','/');
};
$window.localStorage.token = 'foobar';
$http.put(buildApiString('/users/me'), { loggedIn: true }).then(function()
{
return $http.get(buildApiString('/users/me')).then(function(response)
{
$scope.user = response.data
});
});
}]);
Upvotes: 1