I have following app.js file for angular, and i want to add a response interceptor but when i add response interceptor it throws me an error on console
Uncaught Error: [$injector:modulerr]
Below is the file
(function () {
"use strict";
angular.module("builder").config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$provide","$httpProvider",
function ($stateProvider, $urlRouterProvider, $locationProvider, $provide, $httpProvider) {
$httpProvider.responseInterceptors.push('responseObserver');
}]).factory('responseObserver',
function responseObserver($q, $window) {
return function (promise) {
return promise.then(function (successResponse) {
return successResponse;
}, function (errorResponse) {
switch (errorResponse.status) {
case 401:
$window.location = $window.location;
break;
case 403:
$window.location = './403.html';
break;
case 500:
$window.location = './500.html';
}
return $q.reject(errorResponse);
});
};
});
}());
Can anyone guide me what is causing this issue.
You didn't define the angular module 'builder' anywhere. The following format (which your file uses):
angular.module("builder")
means, "use the angular module 'builder' which I have already defined."
The following format:
angular.module("builder",[])
means, "create the angular module 'builder' right here and now (and eliminate any previous one)".
You can create and use at the same time as:
angular.module("builder",[]).config(....
but you must define it somewhere at least once.
Your factory should be changed like below:
.factor('responseObserver', '$window', function responseObserver($window, $q){
});
notice the way I injected $window. You have to annotate the $window, so that injector can recognize the functions/directives/services to be injected.
Related
Tring to add interceptor header for my every request, however, it is giving me below error.
Uncaught Error: [$injector:cdep] Circular dependency found: $http <- Auth <- httpRequestInterceptor <- $http <- $templateRequest <- $route
app.js
var app= angular.module('myDemoApp',['ngRoute'])
app.factory('httpRequestInterceptor', ['Auth', function (Auth) {
return {
request: function (config) {
config.headers['x-access-token'] = Auth.getToken();
return config;
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
Auth Service
(function () {
'use strict';
myDemoApp.factory('Auth', ['$http', '$window', Auth]);
/******Auth function start*****/
function Auth($http, $window) {
var authFactory = {};
authFactory.setToken = setToken;
authFactory.getToken = getToken;
return authFactory;
/*setToken function start*/
function setToken(token) {
if (token) {
$window.localStorage.setItem('token', token);
} else {
$window.localStorage.removeItem('token');
}
}
/*getToken function start*/
function getToken() {
return $window.localStorage.getItem('token')
}
}
})();
You can't do this because.
You have created httpRequestInterceptor which intercepts all $http requests.
Now, you are passing Auth in the httpRequestInterceptor.
If you'll see, Auth uses $http request inside itself.
So, your interceptor can itself cause a http request using Auth.
Hence, its circular error and angularjs wont allow you to do that !
Remove $http from Auth factory OR dont insert a service into interceptor which itself uses $http.
I hope you got, how the infinite loop chain being created, hence a circular dependency error !
Im new to angular js.
Can anyone please tel me why i get an error saying functions in the factory cannot be accessed from the controller.
Error: UserService.getAllCustomers is not a function
This happens when I add
App.service('UserService', function () { })
to the controller.
If this is not added it gives
Error: [$injector:unpr] Unknown
provider:serServiceProvider<-UserService<- UserController
You should have someting like :
angular.module('MyApp')
.factory('serviceName',[
function () {
return function () {
/*your code */
};
}]);
angular.module('MyApp')
.controller('controllerName',['serviceName'
function (serviceName) {
}]);
The userService does not have the "getAllCustomers"
var App= angular.module('myApp', []);
App.controller("MyCtrl", ['UserService', function(UserService) {
UserService.getAllCustomers();
}]);
App.service('UserService', function() {
this.getAllCustomers = function() {
alert('getAllCustomers');
}
});
DEMO
Note: If you removed "UserService" from the app ,so the UserService is not available in the app, but you are injected in controller then angular will check UserService is created or not, if it is not created it will throw the error like Error:
[$injector:unpr] Unknown provider:serServiceProvider<-UserService<-
UserController
I have the following provider:
(function (angular) {
angular.module('app')
.provider('$_Config', ConfigProvider);
function ConfigProvider() {
.... //routes definition
}
ConfigProvider.prototype.$get = function () {
return this;
};
ConfigProvider.prototype.getRoutes = function() {...}
//other prototype functions
})(angular);
In app.js I am using it like this:
app.config(function ($routeProvider, $_ConfigProvider) {
var routes = $_ConfigProvider.getRoutes();
routes.forEach(function(route) {
$routeProvider
.when(route.route, {
.....
})
}
Every thing work fine till it gets to testing. Here is my test:
describe('Provider: $_ConfigProvider', function () {
// load the providers module
beforeEach(module('app'));
// instantiate provider
var $_ConfigProvider;
beforeEach(inject(function (_$_Config_) {
$_ConfigProvider = _$_Config_;
}));
it('Should verify getRoutes function', function () {
var routes = $_ConfigProvider.getRoutes();
expect(Object.prototype.toString.call(routes) === '[object Array]').toBe(true);
});
});
When running the test I am getting the following error:
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:unpr] Unknown provider: $_ConfigProvider
Note: The $_ConfigProvider is injected correctly during run-time.
You are likely not including the file where the provider is defined in in your karma.conf.js dependencies list. See this question:
Include dependencies in Karma test file for Angular app?
I would rename the $_Config to something else, '$' is usually reserved for angular-specific components.
for my web page I have several angular apps. For those apps I want to create a global error handler which tracks errors with codes 500, 401 and so on and displays them as alerts.
Here is what I have so far:
I've created a global error handler module which I then inject in my apps
angular.module('globalErrorHandlerModule', [])
.factory('myHttpInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {
return {
'responseError': function (rejection) {
if(rejection.status == 500){
// show error
}
return $q.reject(rejection);
}
};
}])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
angular.module('myApp', ['globalErrorHandlerModule'])
Now what I'm struggling with is actually displaying the error in an alert. What's the best way to do this? I've tried creating a separate error app and injecting the error module and share a data factory in between, but the data never gets updated in the app. Something like this:
angular.module('globalErrorHandlerModule', [])
.factory('myHttpInterceptor', ['$rootScope', '$q', 'Data', function ($rootScope, $q, Data) {
return {
'responseError': function (rejection) {
if(rejection.status == 500){
// set error
Data.error.message = '500 error';
}
return $q.reject(rejection);
}
};
}])
.factory('Data', function () {
var _error = {
message: "init"
};
return {
error: _error
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
angular.module('globalErrorHandlerApp', ['globalErrorHandlerModule'])
.controller('GlobalErrorCtrl', function ($scope, Data) {
$scope.test = Data.error.message;
});
And then displaying the error as follows:
<div ng-controller="GlobalErrorCtrl">
Error {{test}}
</div>
But as mentioned I only see my initial value, and no updates to the error message. I've also tried broadcasting but that didn't work either. I'm sure there's a better way to implement something like this, I just haven't found it yet. Thanks for any tips pointing me in the right direction.
try with this
angular.module('globalErrorHandlerApp', ['globalErrorHandlerModule'])
.controller('GlobalErrorCtrl', function ($scope, Data) {
$scope.test = Data.error;
});
its a better idea watch an object than a string.
let me know if help you
<div ng-controller="GlobalErrorCtrl">
Error <span> {{test.message}} </span>
</div>
I have the strange issue, that somehow my own provider is not injecting correctly into my app.
This is my provider:
angular.module '1425App'
.provider 'OData',[() ->
#_baseUrl = ''
return {
setBaseUrl: (value) ->
#_baseUrl = value
return
$get: ['$http', '$q', ($http, $q) ->
return {
getAll: (resource) ->
dfd = $q.defer()
$http.get("#{#_baseUrl}/#{resource}").success (res) ->
console.log res
dfd.resolve()
return
return dfd.promise
}
]
}
]
This is my app + config block:
angular.module('1425App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'angular-loading-bar',
'ngAnimate',
'toaster',
'ui.gravatar',
'ngFitText',
'google-maps',
'mm.foundation',
'restangular',
'ui.select2',
'ngTable',
'ngGrid',
'ngCsv',
'ui.date',
'ngDragDrop',
'ui.sortable'
])
.config ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, cfpLoadingBarProvider, baseUrl, ODataProvider) ->
$httpProvider.interceptors.push('httpInterceptor')
ODataProvider.setBaseUrl(baseUrl + '/odata/')
cfpLoadingBarProvider.includeSpinner = false
...
Im getting following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module
1425App due to: Error: [$injector:unpr] Unknown provider:
ODataProvider
This leads to my believe, that its an issue with injecting the provider into my app. Any idea what im missing?
Looking at you pasted snippet issue could be that you have config block appearing before oData provider has been registered. Try setting up the config block after the oDataProvider registration.
Separate out config block from app registration and load it after your provider(s) have been registered. You can only configure the providers that are registered before the specific config block that uses it. This is not the case with constant though you can have them registered in any order.
The above information (which was a bug) is as of 1.2.* version of angular, with 1.3 you can register providers even after the config block.