i have my angular service and controller, i need to pass the data between service to controller to get value for voucher_code
Angular Service:
myApp.service('tradeData', function ($http) {
var service ={};
var voucher_code;
service.postTrade = function(trade){
console.log(trade)
console.log("TEST")
var promise = $http.post('tradein', trade);
promise.
then(function successCallback(response) {
angular.extend(trade, response.tradeData);
//console.log("======="+response.data)
voucher_code = JSON.stringify(response.data.voucher_code, null, 4); // (Optional) beautiful indented output.
console.log("test123",voucher_code);
return voucher_code;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
return promise;
};
return service;
})
Angular Controller:
myApp.controller('ModalInstanceCtrl', function($scope, $uibModalInstance, items, PersonalInfoService, tradeData) {
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
}
$scope.personal = PersonalInfoService;
$scope.printToCart = function(printSectionId) {
var innerContents = document.getElementById(printSectionId).innerHTML;
var popupWinindow = window.open('', '_blank', 'width=550,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWinindow.document.open();
popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="css/print.css" media="screen, print" /></head><body onload="window.print()">' + innerContents + '</html>');
popupWinindow.document.close();
}
$scope.Product = tradeData;
console.log("sfsdff" , tradeData.voucher_code);
// console.log("santo", voucher_code);
// console.log("santo", service);
})
Any idea to pass the values of voucher_code from service to controller
Use this in your controller:
tradeData.postTrade().then(function(voucher_code) {
$scope.voucher_code = voucher_code;
)};
postTrade method returns the promise. So you can use the data it returns (get resolved with) by using the then method.
Related
Im using angularjs in MVC.
Here My Controller.js:
//Get User By ID
$scope.GetUserById = function (UID) {
var Get = UserService.GetUserById(UID);
Get.then(function (response) {
$scope.User = response.data;
alert($scope.User.Address);
});
};
services.js:
//Get By ID
this.GetUserById = function (UID) {
debugger;
return $http.get("../api/UsersData/GetUserById?UID=" + UID);
};
When I'm using the debugger, the alert message is displayed. If I'm not debugging then it doesn't return a value.
What is the issue in my code?
How to display the value to html page?
You should get it working with few adjustments.
Service.js:
angular.module('myApp').factory('MyService', MyService);
//Avoid Minification Problems
MyService.$inject = [ '$http' ];
function MyService( $http ){
function GetUserById(UID){
return $http.get('../api/UsersData/GetUserById?UID=' + UID)
.then( function (response) {
if(response){
return response;
}
});
}
//Expose Method to External Calls
return {
GetUserById : GetUserById
}
}
Controller.js:
angular.module('myApp').controller('MyController', MyController);
MyController.$inject = [ '$scope', 'MyService' ];
function MyController( $scope, MyService ){
$scope.GetUserById = function(UID){
MyService.GetUserById(UID).then( function(response){
$scope.User = response.data;
alert($scope.User.Address);
});
}
}
Make sure what response is actually returning with a $log or using console.log in order to properly alert the address. Do this check also in the service, for instance you should check if response.address exists.
You can also use a Service instead of a Factory.
I have a service which get data from a file(path is given by the controller) and return a promise - then another service that create a object with properties using the returned data from the last service.
My problems are:
The getDataService runs before controller so it has no path from which to fetch data => nothing in return(an error)
Provider 'GetDataService' must return a value from $get factory method.
I need to keep this structure because I'll have more controllers with different paths to give
I'm also opened to other solutions but I need to make sure that datas are loaded before the template get populated. I've tried to call SetProperties service first with getData service into it - but still getData.js is executed first
getdata Service
angular.module('myApp').factory('GetDataService',['$http', function($http) {
var getData = function(path){
return $http.get(path).then(function(result) {
return result.data;
});
};
}]);
setProperties service
angular.module('myApp').service('PageProperties',['$http', function($http) {
this.setProps = function(page, data) {
some code here
var properties = {
isCenterActive : isActive_val,
//header elements
titleClass : page,
title : data.titles[page],
//footer elements
leftLink : leftLink_val,
leftFooterClass: leftLink_val,
leftTitle: data.titles[leftLink_val],
centerLink : centerLink_val,
centerFooterClass: data.titles[centerLink_val],
centerTitle : centerTitle_val,
rightLink : rightLink_val,
rightFooterClass: rightLink_val ,
rightTitle : data.titles[rightLink_val],
}
return properties;
}
}]);
controller
angular.module('myApp', [])
.controller('meniuController', ['$http', '$stateParams', '$scope', 'GetDataService', 'PageProperties',
function($http, $stateParams, $scope, GetDataService, PageProperties){
var page = "meniu";
$scope.language = $stateParams.lang;
var path = '_global/views/services/json/' + $stateParams.lang + '_data.json';
/*PageProperties.setProps(page, path).then(function(data){
//some code here
});*/
GetDataService.getData(path).then(function(data){
$scope.props = PageProperties.setProps(page, data);
}).catch(function(){
$scope.error = 'Unable to get data';
});
}])
Thanks in advance!!
The error says your GetDataService provider (defined as factory) doesn't return anything
angular.module('myApp').factory('GetDataService',['$http', function($http) {
var getData = function(path){
return $http.get(path).then(function(result) {
return result.data;
});
};
// you need to actually return something
return { getData: getData };
}]);
Then you can make your PageProperties use GetDataService
angular
.module('myApp')
.service('PageProperties',['GetDataService', function(GetDataService) {
this.getProperties = function(path) {
return GetDataService.getData(path).then(/*transform here*/)
}
I havea factory call HTTP end point to fetch user:
.factory('me', function($resource, VAS_API_URL, $q) {
return {
getUser: function() {
var deferred = $q.defer();
var url = VAS_API_URL + 'api/me';
$resource(url)
.get(function(user) {
deferred.resolve(user);
}, function(response) {
deferred.reject(response);
});
return deferred.promise;
}
};
})
I use this factory in many controllers and, i bind the data to the DOM successfully, but at times i want to use the data returned from the factory in my controller like to save the user name with a notification so i had to do the following:
.controller('createNotificationCtrl', function($scope, VAS_API_URL, me) {
var Burl = VAS_API_URL + 'api/notification';
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.message = $scope.message;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
})
I had to creat $scope.item = {}; in the factory call so i could get the displayName then send the object to save a notification but what if i want to save also another filed from another factory. How it could be done?
The factory should create the object and hold it as a state.
The controller's should use the reference from the factory and update it for everyone.
factory code sample:
this.stateObj = {};
....
....
this.getUser = function(){
var promise = $http.get(url);
promise.then(function(res){
// update stateObj
});
return promise;
}
ctrl code sample:
factory.getUser().then(function(res){
$scope.stateObj = factory.getStateObj();
});
I'm new in angularjs and i have a problem trying to use $scope inside a $http.
inside $http i can see data but outside service i get null.
Console.log($scope.data) inside service I get data:
Console.log($scope.data) outside always null:
mycode :
(function (app, ng) {
'use strict';
app.controller('mainController', ['$scope', 'ServicePatient', function ($scope, ServicePatient) {
$scope.data = null;
ServicePatient.all().success(function (data) {
$scope.data = data;
});
$scope.sortType = 'last_Name'; // the default sort type
$scope.sortReverse = false; // the default sort order
$scope.search = ''; // the default search/filter term
$scope.filterEnabled = '';
$scope.setEnabled = function(status){
$scope.filterEnabled = status;
if(status){
angular.element(document.querySelector( '#enabledFalse')).removeClass('active-btn');
angular.element(document.querySelector( '#enabledTrue')).addClass('active-btn');
} else {
angular.element(document.querySelector( '#enabledTrue')).removeClass('active-btn');
angular.element(document.querySelector( '#enabledFalse')).addClass('active-btn');
}
}
console.log($scope.data);
}]);
app.service('ServicePatient', ['$http', function ($http) {
function all() {
return $http({
url: 'http://54.165.192.65/ekare/ws6.php?request=patient',
method: 'GET'
});
}
return {
all: all
}
}]);
}(angular.module('app', []), angular));
I have an angular service and a controller interacting. The service usings the $interval to poll the server. I know this returns a promise, however it uses $http to make an call to the server, which ALSO returns a promise and the chaining of the promises is not happening the way I would expect.
SERVICE
(function () {
'use strict';
var serviceId = "notificationService";
angular.module('app').factory(serviceId, ['helpersService', '$interval', '$http', function (helpersService, $interval, $http) {
var defaultOptions = {
url: undefined,
interval: 1000
};
var myIntervalPromise = undefined;
var displayedNotifications = [];
function onNotificationSuccess(response) {
//alert("in success");
displayedNotifications.push(response.data);
return response.data;
}
function onNotificationFailed(response) {
alert("in Failure");
throw response.data || 'An error occurred while attempting to process request';
}
function initializeNotificationService(configOptions) {
var passedOptions = $.extend({}, defaultOptions, configOptions);
if (passedOptions.url) {
myIntervalPromise = $interval(
function() {
//console.log(passedOptions.url);
//return helpersService.getAjaxPromise(passedOptions);
//promise.then(onNotificationSuccess, onNotificationFailed);
$http({
method: 'POST',
url: passedOptions.url
}).then(onNotificationSuccess, onNotificationFailed);
}, passedOptions.interval);
//alert("in initializeNotificationService");
return myIntervalPromise;
}
//return myIntervalPromise;
}
//$scope.$on('$destroy', function() {
// if (angular.isDefined(myIntervalPromise)) {
// $interval.cancel(myIntervalPromise);
// myIntervalPromise = undefined;
// }
//});
return {
// methods
initializeNotificationService: initializeNotificationService,
//properties
displayedNotifications : displayedNotifications
};
}]);
})();
CONTROLLER
(function () {
'use strict';
var controllerId = 'MessageCtrl';
//TODO: INVESTIGATE HAVING TO PASS $INTERVAL TO HERE TO DESTROY INTERVAL PROMISE.
//TODO: HAS TO BE A WAY TO MOVE THAT INTO THE SERVICE
angular.module('app').controller(controllerId, ['notificationService', '$scope', '$interval', function (notificationService, $scope, $interval) {
var vm = this;
// tied to UI element
vm.notifications = [];
vm.initialize = function () {
// initialize tyhe notification service here
var intervalPromise = notificationService.initializeNotificationService({ url: 'api/userProfile/getNotifications', interval: 5000 });
intervalPromise.then(
function (response) {
// NEVER GETS CALLED
var s = "";
//vm.notifications.push(response);
// alert("successful call");
},
function (response) {
var s = "";
// THIS GETS CALLED WHEN THE PROMISE IS DESTROYED
// response = canceled
//alert("failure to call");
},
function(iteration) {
console.log(notificationService.displayedNotifications);
// This gets called on every iteration of the $interval in the service
vm.notifications = notificationService.displayedNotifications;
}
);
// TODO: SEE COMMENT AT TOP OF CONTROLLER
$scope.$on('$destroy', function () {
if (angular.isDefined(intervalPromise)) {
$interval.cancel(intervalPromise);
intervalPromise = undefined;
}
});
};
vm.alertClicked = function (alert) {
alert.status = 'old';
};
// call to init the notification service here so when the controller is loaded the service is initialized
vm.initialize();
}]);
})();
The way this ends up flowing, and I'll do my best to show flow here
1) SERVICE - $interval makes the call with the $http BOTH OF THESE SEEM TO RETURN THEIR OWN PROMISES ACCORDING TO THE DOCS
2) CONTROLLER - intervalPromise's NOTIFY callack is called
3) SERVICE - onNotificationSuccess callback of $http is called
WHAT DOESN'T HAPPEN THAT I WOULD EXPECT
4) CONTROLLER - intervalPromise success callback is never called
Should the return response.data in the onNotificationSuccess handler within the service trigger the then chain in the Controller? It's aware that the promise is returned or seemingly cause the notify callback in the controller is called each time $interval executes, so I'm confused as to where the chain is broken.
IDEAL
$interval calls with $http, the promise from $http is passed up to the controller
then with each iteration new messages are added to the service on a successful call by $interval, then in the controller onsuccess I can check the property of the service and update the UI. Where am I losing the method chain?
I would recommend breaking the usage of $interval outside of service and use it directly in your controller.
The service being provided is the ability to get data from the server and the interval is the means in which to get the data, which is more indicative of the user interface's requirements as to how often the data is retrieved.
What you appear to be doing is to wrap the functionality of the $interval service which is causing a complication for you.
Note: after creating a quick plnkr the report progress event of $interval returns the iteration number (times called) and no other parameters.
Ended up with everything in the controller...
(function () {
'use strict';
var controllerId = 'NotificationCtrl';
angular.module('app').controller(controllerId, ['helpersService', '$scope', '$interval', function (helpersService, $scope, $interval) {
var vm = this;
var intervalPromise = undefined;
// tied to UI element
vm.notifications = [];
function onNotificationSuccess(response) {
//alert("in success");
vm.notifications.push.apply(vm.notifications, response.data);
return response.data;
}
function onNotificationFailed(response) {
//alert("in Failure");
throw response.data || 'An error occurred while attempting to process request';
}
vm.initialize = function () {
intervalPromise = $interval(
function () {
var promise = helpersService.getAjaxPromise({ url: 'api/userProfile/getNotifications' });
promise.then(onNotificationSuccess, onNotificationFailed);
}, 5000);
$scope.$on('$destroy', function () {
if (angular.isDefined(intervalPromise)) {
$interval.cancel(intervalPromise);
intervalPromise = undefined;
}
});
};
vm.alertClicked = function (alert) {
//alert.status = 'old';
};
// call to init the notification service here so when the controller is loaded the service is initialized
vm.initialize();
}]);
})();