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) {
Related
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
}
})();
I am trying to access $location in my controller and I am not having any luck. Below is my controller code.
bwApp.controller('bidding-controller', [
'$window', '$scope', '$rootScope', '$firebase', '$location',
'$compile', '$interval','$bwAppState', 'bidwrangler_api', 'AuctionService',
'CompanyService', 'NavigationService', 'UserService',
function($window, $scope, $rootScope, $firebase, $location, $compile, $interval,
$bwAppState, bidwrangler_api, AuctionService, CompanyService,
NavigationService, UserService) {
$scope.toggle_auction = function(item) {
if ($bwAppState.user.type == "clerk" && !item.listing) {
$window.location.href = "/clerk/" + item.auction.id + "?item=" + item.id;
}
else {
var restore_pos = null;
if ($location.search().section == 'itmes') {
restore_pos = $('.all-items').scrollTop();
$('.all-items').one('scroll', function(){$('.all-items').scrollTo(restore_pos)});
}
else if ($location.search().section == 'user_items'){
restore_pos = $('#your-items').scrollTop();
$('#your-items').one('scroll', function(){$('#your-items').scrollTo(restore_pos)});
}
NavigationService.update_push_state({item: item.id, section: 'auction'});
}
};
}
]);
When I am checking $location.search().section I keep getting an error in the console. If I am outside of $scope.toggleAuction() I have access to it. I have included/injected it correctly into the controller so I don't understand why I can't access it inside of the $scope function.
The error that I receive looks like the following:
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);
}
};
});
I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])