I have created interceptor as follows:
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector) {
// Here I handle my http responses
}
})();
I have other service defined in file myService.js I want to use methods of this service in interceptor above, so I did following changes in the above code :
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector', 'myService'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector, myService) {
// Here I handle my http responses
}
})();
I have got following error:
Uncaught Error: [$injector:unpr] Unknown provider: myServiceProvider <- myService <- ErrorResponseInterceptor <- $http <- $translateStaticFilesLoader
myService.js code :
(function() {
'use strict';
angular.module('sbApp').factory('myService', myService);
myService.$inject = [ '$rootScope', '$http', 'restAPIService', '$log',
'$filter', '$interval', '$location' ];
function myService($rootScope, $http, restAPIService, $log, $filter,
$interval, $location) {
......
return {
add : add,
};
.....
function add(module, event) {
var e = {
..........
}
.......
return $rootScope.myarray.push(e);
}
}
})();
Is it allowed to use myService into interceptor, How can I pass it to interceptor?
To get the instance of service object inside the interceptor use:
$injector.get('serviceName');
Please try something like this:
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector) {
var myService = $injector.get('myService');
// Here I handle my http responses
}
})();
Related
I want to call a service which I defined in DeliverService but when I called it from controller it gives an error of Cannot read propery getRiders of undefined , NO idea why this happened :|
DeliverService.js
angular.module('Deliver')
.service('DeliverService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService", function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getRiders : function(){
return $http.get("Hero.json");
//return $http.get(SettingService.baseUrl + "api/orders");
} }
return service;
}]);
DeliverCtrl.js
use strict';
angular.module('Deliver').controller('DeliverCtrl',['$scope','$state', "SettingService","DeliverService", function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){
});
}]);
Your dependencies aren't in the matching order here. Hence, DeliverService isn't actually injected.
Your controller code should look something like this:
angular.module('Deliver').controller('DeliverCtrl',
['$scope','$state', '$ionicModal', 'MessageService', 'SettingService','DeliverService',
function($scope, $state, $ionicModal, MessageService, SettingService, DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){});
}]);
In DeliverCtrl.js
The injection Parameter and function parameters do not match
It should be like this
['$scope','$state','$ionicModal','MessageService','SettingService','DeliverService', function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService)
In my controller class I fetch the id of specific user from URL and then send it to service OrderService Now in the service I want to retrieve the data of this id from JSON file , How can I achieve this ?
OrderCtrl
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService","$stateParams", function($scope, $state, SettingService, OrderService,$stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function(response){
$scope.orders = response.data.data;
}, function(error){
})
}]);
OrderService.js
angular.module('Orders')
.service('OrderService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getOrderDetails : function(OrderId){
Here I want to retrieve data from JSON file
});
}
}
return service;
}]);
Try to use something like this
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService", "$stateParams", function ($scope, $state, SettingService, OrderService, $stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function (response) {
$scope.orders = response.data.data;
});
}]);
// I act a repository for the remote json collection.
angular.module('Orders').service("OrderService", ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function ($http, $state, $resource, $q, SettingService, $localStorage, MessageService, handleResponse) {
// Return public API.
return ({
getOrderDetails: getOrderDetails
});
// I get all the remote collection.
function getOrderDetails(OrderId) {
var request = $http({
method: "get",
url: '/ajax/order/details', // for example
params: {'id': OrderId}
});
return (request.then(handleResponse.success, handleResponse.error));
}
}]);
angular.module('Orders').service('handleResponse', function ($http, $q, $location) {
return {
error: function (response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (!angular.isObject(response.data) || !response.data.message) {
// Something was wrong, will try to reload
return ($q.reject("An unknown error occurred."));
}
// Otherwise, use expected error message.
return ($q.reject(response.data.message));
},
success: function (response) {
return (response.data);
}
};
});
Project Architecture:
-> public/modules/core/services/home.client.service.js
-> public/modules/core/controllers/home.client.controller.js
-> public/modules/core/controllers/header.client.controller.js
-> public/modules/core/views/header.client.view.html
-> public/modules/core/views/home.client.view.html
I am trying to inject home.client.service into home.client.controller.js
The following code:
angular.module('core').controller('HomeController', ['$scope', 'Authentication', 'HomeService',
function($scope, $q, Authentication, HomeService) {
Returns:
Unknown provider: HomeServiceProvider <- HomeService
Whereas:
angular.module('core',[]).controller('HomeController', ['$scope', 'Authentication', 'HomeService',
function($scope, $q, Authentication, HomeService) {
Returns:
Argument 'HeaderController' is not a function, got undefined
header.client.controller.js looks like:
'use strict';
angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus',
function($scope, Authentication, Menus) {
$scope.authentication = Authentication;
$scope.isCollapsed = false;
$scope.menu = Menus.getMenu('topbar');
$scope.toggleCollapsibleMenu = function() {
$scope.isCollapsed = !$scope.isCollapsed;
};
// Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function() {
$scope.isCollapsed = false;
});
}
]);
home.client.service is:
angular.module('core').service('HomeService', function($http) {
function get(n,idc,cluster,type){
//Return a promise
return $http.post('url/search?idc=' + idc + '&type=' + type + 'cluster=' + cluster , n);
}
return {
get: get
}
});
Can anyone help me correctly inject my service into my controller?
You need the string '$q' in your array as well.
Like this:
angular.module('core').controller('HomeController',
['$scope', '$q', 'Authentication', 'HomeService',
function($scope, $q, Authentication, HomeService) {
I have a factory method as..
(function (angular) {
"use strict";
angular
.module('app')
.factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) {
var markCurrentUserAsContentOwner = function () {
var user = getCurrentUser(true);
user.set('isContentOwner',"true");
user.save(null, {
success: function(savedUser) {
alert("succes");
},
error: function(savedUser,error) {
alert("error");
}
});
};
}]);
})(angular);
Now If I call this method from another service method..
(function(angular) {
'use strict';
angular
.module('app')
.service('ContentOwnerService',
[
'$q', 'UserService'
function($q, userService) {
var servicemethod=function() {
userService.markCurrentUserAsContentOwner();//UserService is the factory name
};
}]);
})(angular);
Its showing an error..Uncaught TypeError: undefined is not a function.
Please anyone help me to resolve this error..
Use $injector service to solve this problem.
Example:
session.factory('redirectInterceptor', ['$injector','$rootScope', '$timeout', '$q', '$window', function($injector,$rootScope, $timeout, $q, $window) {
return {
'request': function(req) {
req.headers['CustomHeader'] = "Be Creative!";
return req || $q.when(req);
},
'response': function(response) {
if (response.data.Status === 'Failed...') {
var AuthenticationService = $injector.get('AuthenticationService');
AuthenticationService.ClearCredentials();
$window.location.href = "/#/login";
$timeout(function() {
$rootScope.sessiondata = true;
}, 5000)
return $q.reject(response);
} else {
return response;
}
}
}}])
I'm injecting controller from external file and I want to do the same thing for the service from external file. It should be registered in factory statement.
Injecting of the controller working
controllers
'use strict';
define(['angular', 'services'], function (angular) {
return angular.module('vcApp.controllers', ['vcApp.services'])
.controller('AuthCtrl', ['$scope', '$injector','AuthService', function($scope, $injector, AuthService) {
require(['auth/authCtrl'], function(authCtrl) {
$injector.invoke(authCtrl, this, {'$scope': $scope, 'AuthService':AuthService});
});
}]);
});
authCtrl
define([], function() {
return ['$scope', '$routeParams', '$location', '$http', 'AuthService', function($scope, $routeParams, $location, $http, authService) {
$scope.signIn = function() {
...
}
$scope.$apply();
}];
});
And now I want to inject service
services
'use strict';
define(['angular'], function (angular) {
angular.module('vcApp.services', [])
.factory('AuthService', ['$http', '$injector', function($http, $injector) {
require(['auth/authService'], function(authService) {
$injector.invoke(authService, this, {'$http': $http});
});
}]);
});
authService
define([], function() {
return ['$http', function ($http) {
return {
login: login
};
function login(username, password) {
var request = $http(...);
return(request);
}
}]
});
When authController calls authService.login(...), it throws error Error: [$injector:undef] Provider 'AuthService' must return a value from $get factory method..
This code was inspired by angular-requirejs-seed project.
As it says, Angular's factory() is expected to return the service object. You may have luck with something like:
define(['angular'], function (angular) {
angular.module('vcApp.services', [])
.factory('AuthService', ['$http', '$injector', function($http, $injector) {
var stub = {};
require(['auth/authService'], function(authService) {
angular.extend(stub, $injector.invoke(authService, this, {'$http': $http}));
});
return stub;
}]);
});
Here you define a stub for the service and extend it, when the service is actually lazy-loaded.
(By the way I think the last 2 arguments of $injector.invoke() are redundant in this case.)
If you want another idea about mixing RequireJS and Angular, that plays well with lazy loading and the r.js optimizer, you may take a look at angular-require-lazy.