Pass value from provider to controller in angularJs - javascript

I'm trying get data from db to UI. Url given via provider is getting the data.
Controller in controller DetailsProvider.getDashboardDetails() is getting null.
var appmod = angular.module('project.DetailDashboardController', []);
appmod.controller("DetailDashboardController", ['$rootScope', '$scope', '$state', 'DetailsProvider',function($rootScope, $scope, $state,DetailsProvider) {
console.log("DetailDashboardController --- ");
$scope.DetList= DetailsProvider.getDashboardDetails()
}]);
})(window, window.angular);
provider which will call the list
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
Thanks in advance for any kind of reply!

You should return promise from your service method and do thenable in your controller.
Root Cause : your are returning the newData which will initalized later after completing the ajax call.Before completing it,you are returning the same variable which will be always null.
In provider,
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
and in controller,
$scope.list = function() {
DetailsService.getDashboardDetails(function(data){
varr holdIt = data.data.DList;
});
};

Related

Pass data between functions in same controller using another service to get data

I get some data through Myservice from another Controller. I can see {{users.data}} from the view, but users.length = 0 ,and $data is empty, that means I can't access to the content of MyService in getData function.. if i replace MyService with json data like
$scope.users=[{..},{..}] it works fine
thank you ..
app.service('MyService', function() {
return data = [];
});
app.controller('tableController', function ($scope,
$filter,NgTableParams,MyService) {
$scope.users= MyService
$scope.usersTable = new NgTableParams({
page: 1,
count: 6
}, {
getData: function(params) {
params.total($scope.users.length);
$scope.da = params.sorting() ? $filter('orderBy')
($scope.users, params.orderBy()) : $scope.da;
$scope.da= params.filter() ? $filter('filter')
($scope.da, params.filter()) : $scope.users;
return $scope.da.slice((params.page() - 1) *
params.count(), params.page() * params.count());
}
}
);
});
When you get your data in the first controller you call MyService.setData(data); The service will store in its local var data and keep it there. Then in the second controller you can retrieve that data by calling MyService.getData()
app.service('MyService', function() {
var ret = {
data: [],
setData: function(inData) {
ret.data = inData;
},
getData: function() {
return ret.data;
}
};
return ret;
});
the first controller 1
app.controller('EventCtrl', ['$scope', 'EventService', 'MyService',
function ($scope, EventService , MyService) {
var baseUrl = '';
$scope.getEvents=function()
{
var apiRoute = 'http://localhost:9811/notification/notification/';
var _Event = EventService.getAll(apiRoute);
_Event.then(function (response) {
$scope.events= response.data;
MyService.data = $scope.events;
MyService.setData($scope.events);
$scope.VarCtrl1= MyService;
},
function (error) {
console.log("Error: " + error);
});
}
$scope.getEvents()
}]);
i updated the service but it doesnt work ..so i modified the first controller like this what do you think?
app.controller('EventCtrl', ['$scope', 'EventService', 'MyService',
function ($scope, EventService , MyService) {
var baseUrl = '';
$scope.getEvents=function()
{
var apiRoute =
'http://localhost:9811/notification/notification/';
var _Event = EventService.getAll(apiRoute);
_Event.then(function (response) {
var data = response.data
MyService.setData(data);
$scope.VarCtrl1= MyService;
},
function (error) {
console.log("Error: " + error);
});
}
$scope.getEvents()
}]);
Thanks for the update of the service now its better ...i can have data in $users and $data in tableController but orderBy need an array but i get this :( when i do consoleLoge($scope.users)
Object {data: Array(0), setData: function, getData: function}data:
Array(9)0: Object1: Object2: Object3: Object4: Object5: Object6:
Object7: Object8: Objectlength: 9__proto__: Array(0)getData:
function ()setData: function (inData)proto: Object
tableController.js:24

Dynamic url for $http get

Here is what i try to do :
Json from "urldatas":
[{ "name" : "John" }]
JS file:
var app = angular.module('app', []);
app.service('service', function($http, $q){
this.getDatas = function () {
var datas = $http.get('urldatas', {cache: false});
return $q.all({datas});
};
app.controller('FirstCtrl', function($scope, service, $http, $timeout) {
var vm = this;
vm.loadData = function () {
var promise = service.getDatas();
promise.then(function (data) {
$scope.datas = data.datas.data;
console.log($scope.datas);
});
};
vm.loadPackages = function () {
var url = "urlPackages" + datas.name;
$http.get(url).then(function (response) {
$scope.MyPackages = response.data;
});
};
So i try to dynamicly change url in $http.get in getPackages, by values from getDatas, but i don't know how to do it. url in console shows "urlPackagesundefinded". Thanks for answers in advance.
$q send multiple requests as an array, not as an object. remove the curly bracket and add a square bracket
var datas = $http.get('urldatas', {cache: false});
return $q.all([datas]);
since you reference the controllerAs remove the scope variables and reference them through vm.
also in then promises response data comes under data property
var promise = service.getDatas();
promise.then(function (response) {
vm.datas = response.data.datas.data;
console.log(vm.datas);
});

AngularJS factory for sharing data between controllers

I have an AngularJS application (1.4.10) and I need to share some data between two controllers.
So I made my factory:
.factory('CardsForService', function($http, URL){
var service = {
"block_id": '',
"service_id": ''
};
service.save_data = function(block_id, service_id){
service.block_id = block_id;
service.service_id = service_id;
};
service.get_data = function(){
return service;
};
return service;
})
I insert the data in the first controller:
$scope.open = function(id, type){
console.log(id +" "+type);
CardsForService.save_data(id, type);
...
And I try to get the data in another controller, like this:
$scope.$on('$routeChangeSuccess', function() {
if (algo_to_used == "service"){
var data = CardsForService.get_data();
console.log(data);
} else {
}
});
The console.log output this:
Object {block_id: "", service_id: ""}
If I try the same get_data() function in the same controller where I call the save_data() function I have the correct results.
What am I missing?
Change Factory Like this
app.factory('CardsForService', function(){
var service = {
"block_id": '',
"service_id": ''
};
var save_data = function(block_id, service_id){
service.block_id = block_id;
service.service_id = service_id;
};
var get_data = function(){
return service;
};
return{
saveData:save_data,
getData:get_data
}});
And in controllers
app.controller('FirstCtrl',function(CardsForService){
CardsForService.setData(id, type);
});
app.controller('SecondCtrl', function($scope, CardsForService){
$scope.data = CardsForService.getData();
});
This sounds like it could be a timing issue. Data from a service like this isn't reactive. Here's a snippet that should help visualize it.
var app = angular.module("demo", []);
app.factory("MySvc", function() {
var data = {};
data.setData = function(key, value) {
this[key] = value;
}
data.getData = function(key, def) {
return key in this ? this[key] : def;
};
return data;
});
app.controller("test1", ["$scope", "MySvc", "$timeout",
function($scope, MySvc, $timeout) {
$timeout(100).then(function() {
MySvc.setData("foo", "bar");
$scope.data = MySvc.getData("foo");
});
}
]);
app.controller("test2", ["$scope", "MySvc", "$timeout",
function($scope, MySvc, $timeout) {
$timeout(500).then(function() {
$scope.data = MySvc.getData("foo", "baz");
});
}
]);
app.controller("test3", ["$scope", "MySvc",
function($scope, MySvc) {
$scope.data = MySvc.getData("foo", "asdf");
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js "></script>
<div ng-app="demo">
<pre ng-controller="test1">Test 1: {{ data }}</pre>
<pre ng-controller="test2">Test 2: {{ data }}</pre>
<pre ng-controller="test3">Test 3: {{ data }}</pre>
</div>
Ok I solved the problem. Basically before I was using this code for the redirect to the new page:
$window.location.assign('/cards/service');
And now I switched to this code:
$location.path('/cards/service');
And it's working.
The only thing is that when it wasn't working when I redirect the page the console in the chrome inspector refresh for every reloading, now the console do not refresh. Can someone tell me the difference between those two functions?

How to retrieve data via asynchronous call

I am trying to use promise and service to set the data from http request.
I have something like this
angular.module('myApp').controller('productController', ['$scope', 'testService',
function($scope, testService) {
testService.getProducts().then(function(products){
console.log(products);
})
//getFirstProduct is trigger by ng-click user action.
$scope.getFirstProduct = function(){
var t = testService.getFirstProduct();
console.log(t);
}
}
]);
angular.module('myApp').service('testService', ['Product', '$q',
function(Product, $q) {
var products, firstProduct;
var getFirstProduct = function(){
return firstProduct;
}
var setFirstProduct = function(product) {
firstProduct = product;
}
var getProducts = function() {
var deferred = $q.defer();
//Product is a $resource object to send an http request
Product.query({
id: 123
}, function(result) {
setFirstProduct(result.first);
deferred.resolve(classes);
});
return deferred.promise;
}
return {
setFirstProduct: setFirstProduct,
getProducts: getProducts,
getFirstProduct: getFirstProduct
};
}
]);
I need to be able to get First product but I am not sure how to fix this. Can anyone help me about it? Thanks a lot
I see a number of errors in the code such as missing semicolons, mistyped variable/function names, and that setProducts was clobbering its variable.
Also, added $q, as mentioned by #manube
The following should work better:
angular.module('myApp').controller('productController', ['$scope', 'testService',
function($scope, testService) {
testService.getProducts().then(function(products){
console.log(products);
})
//getFirstProduct is trigger by ng-click user action.
$scope.getFirstProduct = function(){
var t = testService.getFirstProduct();
console.log(t);
}
}
]);
angular.module('myApp').service('testService', ['Product', '$q',
function(Product, $q) {
var products, firstProduct;
var getFirstProduct = function(){
return firstProduct;
}
var setFirstProduct = function(product) {
firstProduct = product;
}
var getProducts = function() {
var deferred = $q.defer();
//Product is a $resource object to send an http request
Product.query({
id: 123
}, function(result) {
setFirstProduct(result.first);
deferred.resolve(classes);
});
return deferred.promise;
}
return {
setFirstProduct: setFirstProduct,
getProducts: getProducts,
getFirstProduct: getFirstProduct
};
}
]);

angularjs ng-repeat not updating view when new data comes in

I have a service which will make a call to the server and returns the data. I am binding service to a variable on scope.
Example:
Let the service be DataModelService
in the controller : $scope.data = DataModelService
in the view <div ng-repeat="value in data.persons">{{value.name}}</div>
My Code :
This is how my code looks like:
/**DataModelService**/
factory('DataModelService', [
'DataService',
function (DataService) {
var service;
service = {
changeState: function (params) {
DataService.changePersonState(params)
.then(function (response) {
service.loadData(response.data);
});
},
loadData: function (responseData) {
service.persons = responseData.persons;
}
}
return service;
}
]);
/**DataService**/
factory('DataService', ['$http',
function ($http) {
return {
changePersonState: function (params) {
return $http.post("url", params);
}
}
}
]);
/**DataController**/
.controller('DataController', ['DataModelService',
function (DataModelService) {
$scope.data = DataModelService;
}
]);
/view/
<div ng-repeat = "person in data.persons" >{{person.name}} </div>
On the view I am doing a ng-repeat on a key in data i.e. ng-repeat="value in data.persons"
and also I have an option to change the state of person to active or inactive, so whenver i make a change to the state of the person, a call is sent to the server and data is set into the Service and as it is binded to the view, it should automatically update the data. But whats happening in my case, ng-repeat is not removing old data and instead it is appending new data to the old data.
For me its not good approach to write promise callback (then) into service. Because in your case, DataModelService returns data with some delay but not promise. And we don't know when.
So the way to make it work to add basic $timeout and fetch data from service by using other method.
So my suggestion is Demo
and your fixed example: Demo2
If we will take your example, it should be like:
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function ($scope, DataModelService, $timeout) {
$scope.alertSwap = function () {
DataModelService.changeState('ff');
$timeout(function(){
$scope.data = DataModelService.getResponse();
}, 10);
}
});
fessmodule.$inject = ['$scope', 'Data', '$timeout'];
/**DataModelService**/
fessmodule.factory('DataModelService', [ 'DataService',function (DataService) {
var value = [];
var service = {
changeState: function (params) {
DataService.changePersonState(params)
.then(function (response) {
value = response.persons;
});
},
getResponse : function(){
return value;
}
}
return service;
}
]);
/**DataService**/
fessmodule.factory('DataService', ['$q',function ($q) {
var data = { // dummy
persons: [{
name: "Bob"
}, {
name: "Mark"
}, {
name: "Kelly"
}]
};
var factory = {
changePersonState: function (selectedSubject) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
} //function
]);

Categories