I have an angular app and I want to retain some values between controllers using angular service
Here is my base controller:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
})();
Now I want to add a service I can later fill with key-value pair data. So I tried adding the following:
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
and now it looks like this:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
})();
Here I am stuck. How would I go about injecting values (MyKey and MyValue) into my service? I am newbie with Angular so that makes it hard
Try adding functions to handle your data.
app.service("DataService", function () {
var myData = [];
function addItem(key, value){
var data_item = {Key: key, Value: value);
myData.push(data_item);
}
function getData(){
return myData;
}
return {
add: addItem,
get: getData
}
});
In your controller, use it like
DataService.add('key', 'value');
DataService.get();
change it to
app.service("DataService", function () {
var data_item = {};
return{
function somename(MyKey,MyValue){
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
}
}
});
and from your controller call it as
DataDervice.somename(MyKey,MyValue)
Related
OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();
App.factory('menuService', function ($http) {
var urlBase = 'Services/MenuService.asmx/GetAllMenu';
var factory = {};
factory.getAllMenus= function () {
return $http.get(urlBase);
};
return factory;
});
Controller:
App.controller("sampleController", function ($scope, menuService) {
$scope.List = [];
var menuData=function(data, status){
$scope.List = data;
console.log($scope.List);
}
menuService.getAllMenus().success(menuData);
});
/// Working perfect...
How can i use same service by other controller?
I've tried this one but wrong...
App.controller("viewDetailMenu", function ($scope, menuService, $stateParams) {
$scope.menu = menuService.getMenu($stateParams.id);
});
Here I share image how it look..
Please help me!...
You need to have all functions/methods defined if you want to use them. You getMenu function/method is not defined so it will generate an error. Please look at below code. You can add number of functions. You factory is share by all controllers so you can use it in any controller.
App.factory('menuService', function ($http) {
var urlBase = 'Services/MenuService.asmx/GetAllMenu';
var factory = {};
factory.getAllMenus= function () {
return $http.get(urlBase);
},
factory.getMenu=function(id){
return $http.get(urlBase +"/ID="+ id) // write it according to your API.
}
return factory;
});
And then,
App.controller("viewDetailMenu", function ($scope, menuService, $stateParams) {
$scope.menu = menuService.getMenu($stateParams.id).success(function(data,status){
}).error(function(data,status){
});
});
In my application, I have a service creating a new structure with two json files. So, I use $q.all to use them in a same time.
angular.module('myApp', []).factory('myService', ['$http', '$q', function ($http, $q) {
var myStructure = function () {
var firstJson = $http.get('datas/firstJson.json');
var secondJson = $http.get('datas/secondJson.json');
return $q.all([firstJson, secondJson]).then(function (values) {
var myMap = new Map();
/*
treatment on myMap
*/
return myMap.values();
});
}
return myStructure();
}]);
So, I use this service in myController by using myService.then
var myApp = angular.module('myApp');
myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
myService.myStructure.then(function(value){
$scope.myStructure = value;
});}]);
Finally, when I use {{myStructure}} in my HTML page, after instantiate myApp with ng-controller, the page display {} (an empty object).
Thank you in advance for your help.
Move the myMap logic inside resolve callback in the controller
Service:
angular.module('myApp', []).factory('myService', ['$http', '$q', function ($http, $q) {
var myStructure = function () {
var firstJson = $http.get('datas/firstJson.json');
var secondJson = $http.get('datas/secondJson.json');
return $q.all([firstJson, secondJson]);
}
return myStructure();
}]);
Controller:
var myApp = angular.module('myApp');
myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
myService.myStructure.then(function(values){
var myMap = new Map();
/*
treatment on myMap
*/
$scope.myStructure = myMap.values();
});
}]);
So I created with angular a small factory to get my local json file now I wanna pass that data to my controller but it can't find the factory name and says 'unresolved variable'.
Here is the snippet of my code what I guess is relevant for now.
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
});
})();
My goal is just to console log the $scope.teams, than I can do more with the data.
you should include "dataFactory" inside your controller
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
}); })();
I believe you need to pass your factory into the controller:
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
I'm new in AngularJS - I can't figure out why I get the error mainDataService.refreshStatus is not a function in the $scope.clickMe function. I see the mainDataService variable is an empty object besides its initialization. What am I doing wrong here ?
var mainDataService = {};
var firstModule = angular.module('myModule', ['ngRoute', 'ngAnimate']);
(function () {
var mainDataServiceInjectParams = ['$http', '$q'];
var mainFactory = function ($http, $q) {
mainDataService.refreshStatus = function (id) {
return $http.get('/api/values/' + id).then(function (results) {
return results.data;
});
};
return mainDataService;
};
mainFactory.$inject = mainDataServiceInjectParams;
firstModule = firstModule.factory('mainService', mainFactory);
}());
firstModule.controller('myCtrl', function ($scope, $http) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainDataService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
You need to use the dependency injection mechanism to load your own services.
Put the mainDataService declaration in a local scope and inject the mainService into myCtrl:
var firstModule = angular.module('myModule', ['ngRoute', 'ngAnimate']);
(function () {
var mainDataServiceInjectParams = ['$http', '$q'];
var mainFactory = function ($http, $q) {
var mainDataService = {};
mainDataService.refreshStatus = function (id) {
return $http.get('/api/values/' + id).then(function (results) {
return results.data;
});
};
return mainDataService;
};
mainFactory.$inject = mainDataServiceInjectParams;
firstModule = firstModule.factory('mainService', mainFactory);
}());
firstModule.controller('myCtrl', function ($scope, $http, mainService) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
Even better, you should explicitly assign the dependencies into the controller, so that your code still works after minifcation (as you already did it for the service):
firstModule.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope', '$http', 'mainService'];
function myCtrl($scope, $http, mainService) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
As you see, if you use normal function definitions, you can make use the function hoisting of Javascript and write the functions at the end while having the relevant code at the top. It's the other way round as in your example of the service.
Supply mainService to controller
firstModule.controller('myCtrl', function ($scope, $http, mainService) {
and then use it in the function
mainService.refreshStatus
I think you immediately invoked function is not invoked so mainDataService still reference the object you set at the first line
(function(){})()
rather than
(function(){}())