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();
});
}]);
Related
So I have two modules each one with one with its own controller and I need to pass an object between them, I seen this can be done with a service, I tried some stuff but I keep getting an "$injector" error in the second module/controller. Please help fix this.
This is my first module/controller with its service:
var appIndex = angular.module("AppIndex", ['datatables', 'datatables.bootstrap', 'ui.select']);
appIndex.service('sharedData', function () {
this.data = {};
this.setData = function (newData) {
this.data = newData;
return this.data;
};
this.getData = function () {
return this.data;
};
});
appIndex.controller("IndexController", function ($scope, $http, $window, sharedData) {
sharedData.setData($scope.referencia);
});
And this is my second module/controller:
var appCna = angular.module("AppCna", ['ui.select', 'AppIndex']);
appCna.controller("CnaController", function ($scope, $http, $window, sharedData) {
$scope.referencia = sharedData.getData();
});
You need to call setData in your first controller
appIndex.controller("IndexController", function ($scope, $http, $window, sharedData) {
sharedData.setData($scope.referencia);
});
So in the end I finally stop trying to use a service to my purpose of passing an object between two modules and what I did was to use the LocalStorage function.
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;
}
})();
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)
If I need a to use a factory from another module do I need to add first the DI of the module to my current module and after that add the DI of the factory to the current factory? Or can I just add the factory itself (without its module)?
So if above its true the only use of Di in modules is for that use... or am i missing something else?
var myApp = angular.module('myApp', []);
myApp.service('myService', function() {
// do some stuff
});
myApp.controller('otherCtrl', function($scope, myService) {
// do some stuff
});
inject myApp module into otherApp module and use service myService:
var otherApp = angular.module('otherApp', ['myApp']);
otherApp.controller('myCtrl', function($scope, myService) {
$scope.myService = myService;
});
declare modules with dependecies.
var baseApp = angular.module("ERMSApp", ['ngSanitize', 'ngRoute', 'ngTable']);
var baseApp1 = angular.module("ERMSApp1", ['ERMSApp', 'ngSanitize', 'ngRoute', 'ngTable']);
declaring service.
baseApp.factory("getEmployeesService", function ($http) {
var promise;
var getEmployeesService = {
getEmployees: function () {
if (!promise) {
var promise = $http.get("/Timesheet/GetEmployees").then(function (result) {
return result;
});
}
return promise;
}
}
return getEmployeesService;
});
using service in another module
baseApp1.controller("leaveOnBehalfCtrl", function ($scope, $http, $filter, $sce, ngTableParams, $compile, getEmployeesService) {
getEmployeesService.getEmployees().then(function (data) {
$scope.employees = data.data;
})
});
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(){}())