I'm using a controller to call a service that will make an $http request, but right now I've only set my service to return a string because I want to make sure it works and is calling properly.
When I run it, I get the following error:
TypeError: monitorData.requestEvent(...).success is not a function
My code below:
Controller
(function() {
angular
.module('monitorApp')
.controller('eventCtrl', eventCtrl);
eventCtrl.$inject = ['$scope', '$routeParams', 'monitorData'];
function eventCtrl($scope, $routeParams, monitorData) {
var vm = this;
vm.eventid = $routeParams.eventid;
vm.event = {};
vm.getData = function(eventid) {
console.log("getData variable accessed");
monitorData.requestEvent(eventid)
.success(function(data) {
console.log(data);
})
.error(function(e) {
console.log("Error");
});
return false;
};
vm.getData(vm.eventid);
}
})();
Service
(function() {
angular
.module('monitorApp')
.service('monitorData', monitorData);
monitorData.$inject = ['$http'];
function monitorData($http) {
var requestEvent = function(eventid) {
var gas = "Event " + eventid + " requested.."
console.log(gas);
return gas;
};
return {
requestEvent : requestEvent,
};
}
})();
In order to be chained, it should return a settled promise.
monitorData.$inject = ['$http', '$q'];
function monitorData($http, $q) {
var requestEvent = function(eventid) {
var gas = "Event " + eventid + " requested.."
console.log(gas);
return $q.resolve(gas);
};
return {
requestEvent : requestEvent,
};
}
And by the way, success and error are deprecated legacy methods. It is always then and catch now.
success and error are part of the promise and you are not returning promise.
To make it work,you should use defer which resolve to success
and return promise which later chained with .success and .error
monitorData.$inject = ['$http','$q'];
var defer = $q.defer();
function monitorData($http) {
var requestEvent = function(eventid) {
var gas = "Event " + eventid + " requested.."
defer.resolve(gas)
return defer.promise;
};
return {
requestEvent : requestEvent,
};
}
Related
I am trying to call a child service function in Main Controller.
But I am getting error on than in profile function.
This is my profile function inside main controller.
App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
var theClient = $cookieStore.get('UserData') || {};
$scope.profile = function(theClient) {
var getCurrentClient = theClient;
var getOrganizationId = $rootScope.globalSession.OrganizationId;
if($rootScope.globalSession.UserRole == "Admin")
{
if (getOrganizationId) {
ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {
$scope.myprofile = getClientResponse[1];
$location.path("/profile");
}
else {
toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
}
});
}
}
};
)};
This is Service of another controller whom function "getClient" I am calling in profile function.
App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
var theClient = $cookieStore.get('UserData') || {};
return {
getClient: function() {
if(theClient.OrganizationId) {
//API Call
var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
function(aGetClientResponse) { //Success Callback
return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
},
function(aGetClientResponse) { //Error Callback
return [aGetClientResponse.status,''];
});
}
return promise;
},
setClient: function(aClient) {
theClient = aClient;
$cookieStore.put('UserData', theClient);
}
}
});
Need Help. cant figure out the Problem. Thanks in advance!
Change your service to just return a promise and handle that promise in your controller using then
The service directly returns API call, no then in service
var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)
Here is your service:
App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE, $q) {
var theClient = $cookieStore.get('UserData') || {};
return {
getClient: function() {
if(theClient.OrganizationId) {
var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER)
}
else {
var promise = $q.reject();
}
return promise;
},
setClient: function(aClient) {
theClient = aClient;
$cookieStore.put('UserData', theClient);
}
}
});
Now, the controller handles the success and failure response using then
ClientService.getClient(getOrganizationId).then(function(){},function(){})
Here is your controller, observe then
App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService) {
var theClient = $cookieStore.get('UserData') || {};
$scope.profile = function(theClient) {
var getCurrentClient = theClient;
var getOrganizationId = $rootScope.globalSession.OrganizationId;
if($rootScope.globalSession.UserRole == "Admin")
{
if (getOrganizationId) {
ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
var response = [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
if(response[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {
$scope.myprofile = response[1];
$location.path("/profile");
}
else {
toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
}
},
function(aGetClientResponse) { //Error Callback
return [aGetClientResponse.status,''];
});
}
}
};
)};
In getClient() the code looks like this:
if(theClient.OrganizationId) {
//API Call
var promise = ... some stuff ...;
}
return promise;
So if the condition is false you return undefined which doesn't have a .then property.
You should make sure that a function which returns a promise always returns a promise. If you want to signal that a missing id is an error then just return $q.reject(something) for an already rejected promise.
I'm not sure it this works, but instead of returning a object with the functions inside, have you tried to declare them as part of the factory object? I have some declared like this and they are working, so have a try:
App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
var theClient = $cookieStore.get('UserData') || {};
var function = {
getClient: function() {
if(theClient.OrganizationId) {
//API Call
var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
function(aGetClientResponse) { //Success Callback
return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
},
function(aGetClientResponse) { //Error Callback
return [aGetClientResponse.status,''];
});
}
return promise;
},
setClient: function(aClient) {
theClient = aClient;
$cookieStore.put('UserData', theClient);
}
}
return function;
});
You can have a try with this too:
Define the services in the controller declaration (and remove one rootScope, its duplicated):
App.controller("globalCtrl", ['$scope','$rootScope','$window','$location','$cookieStore','toastr','ClientService', function($scope,$rootScope, $window, $location, $cookieStore, toastr, ClientService){
[...]
}]);
Try something like this to ensure that there is always a promise object available.
getClient: function() {
var deferred = $q.defer();
if(theClient.OrganizationId) {
//API Call
$http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
function(aGetClientResponse) { //Success Callback
deferred.resolve(aGetClientResponse);
},
function(aGetClientResponse) { //Error Callback
deferred.resolve(aGetClientResponse);
});
}else{
deferred.reject('Missing OrganizationId');
}
return deferred.promise;
}
In the else part you can return dummy promise with either resolve($q.resolve()) or reject($q.reject()) status.
JS :
getClient: function() {
if(theClient.OrganizationId) {
//API Call
var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
///your rest code
return promise;
}else{
return $q.reject();
}
}
With $q.reject() it will call error handler in profile call.So,add error handler callback as second parameter
ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
//success code
},
function(){ //add it in your script
//check error here
});
I have a demo application where I have a controller which has a factory as dependency and factory itself depends on another service. My code is as follows:
var app = angular.module('sampleApp', ['ui.router']);
app.service("someServ", function(){
this.sendMsg = function(name){
return "Hello " + name;
}
})
app.factory("appFactory", function ($http, someServ) {
function getData(url) {
return $http.get(url);
}
function foo(){
var text = someServ.sendMsg("Monotype");
alert(text);
}
return {
getData : getData,
foo : foo
}
})
var productsController = function ($scope, $http, appFactory) {
var pct = this;
pct.url = "http://mysafeinfo.com/api/data?list=englishmonarchs&format=json";
var jsonDataPromise = appFactory.getData(pct.url);
jsonDataPromise
.then(function (response) {
pct.jsonData = response.data;
}, function (err) {
console.log("Error is: " + error);
});
pct.profun = function(){
appFactory.foo();
}
};
app.controller("productsController", productsController);
productsController.$inject = ['$scope', '$http', 'appFactory'];
I have to test with karma using Jasmine 2.4 as testing framework. I have tried many online tutorials but getting totally confused as everyone tries to do something different. Some use $provide to mock the service, some simply inject the actual service/factory and use a reference, some do not give any example of passing arguments to services.
Can someone please tell me how to do unit testing in simple terms. I have already tried doing something like this:
describe('unit testing of service and controller', function(){
beforeEach(module('sampleApp'));
var prodCtrl, $prodScope, mockfactory, mockservice;
beforeEach(function(){
mockservice = {
sendMsg : function(name){
return name;
}
}
module(function($provide){
$provide.value("someServ", mockservice);
});
inject(function($rootScope, $controller, $http, $q, appFactory){
appFactory = appFactory;
spyOn(appFactory, 'getData');
spyOn(appFactory, 'foo');
$prodScope = $rootScope.$new();
prodCtrl = $controller('productsController', {
$scope: $prodScope, $http: $http, appFactory:appFactory
});
});
});
it('appFactory has method getData and foo', function(){
appFactory.getData();
appFactory.foo();
expect(appFactory.getData).toHaveBeenCalled();
expect(appFactory.foo).toHaveBeenCalled();
})
it('productsController gets a promise back from getData', function(){
var url = "sample url";
var myPromise = prodCtrl.getData(url);
myPromise.then(function(){console.log("Promise returned");})
})
it('foo calls service method sendMsg', function(){
prodCtrl.profun();
expect(mockservice.sendMsg).toHaveBeenCalled();
})
});
I was finally able to solve this issue. My code looks like this:
var app = angular.module('sampleApp', []);
app.service("someServ", function(){
this.sendMsg = function(name){
return "Hello " + name;
}
})
app.factory("appFactory", function ($q, someServ) {
function getData() {
var defer = $q.defer();
defer.resolve("Success message");
return defer.promise;
}
function foo(){
var text = someServ.sendMsg("Monotype");
alert(text);
}
return {
getData : getData,
foo : foo
}
})
app.controller("mainController", ['$scope', '$http','appFactory', function($scope, $http, appFactory){
var mct = this;
mct.printData = function(){
var myPromise = appFactory.getData();
myPromise
.then(function(data){
alert("Promise returned successfully. Data : " + data);
}, function(error){
alert("Something went wrong.... Error: " + error);
})
}
mct.showMsg = function(){
appFactory.foo();
}
}]);
The test case looked like this:
describe('unit testing', function(){
var jsonData = {
name: "Aosis",
id: 12345
}
beforeEach(module('sampleApp'));
beforeEach(module(function($provide){
$provide.service("someServ", function(){
//this.sendMsg = function(param){}
this.sendMsg = jasmine.createSpy('sendMsg').and.callFake(function(param){})
});
$provide.factory("appFactory", function(someServ, $q){
function getData(){
var defer = $q.defer();
defer.resolve("Success message");
return defer.promise;
}
function foo(){
var facParam = "some text";
someServ.sendMsg(facParam);
}
return {
getData : getData,
foo : foo
}
});
}));
var $scope, mainController, appFactoryMock, someServMock;
beforeEach(inject(function($rootScope, $controller, $http, $q, appFactory, someServ){
appFactoryMock = appFactory;
someServMock = someServ;
$scope = $rootScope.$new();
mainController = $controller("mainController", {
$scope : $scope,
$http : $http,
appFactory : appFactoryMock
});
}));
// Tests go here....
});
Here, I have mocked service method as jasmine spy and specified the function that should get executed usingand.callFake(function(){.....}). A fake factory has been created and its methods have been spied upon. I tried to create fake factory similar to service using jasmine.createSpy but return {
getData : getData,
foo : foo
} was giving error. Hence, I did that.
Anyone, else if has better solution or some other explanation, please share.
I have an Angular service that looks like this:
(function () {
'use strict';
var serviceId = 'currentUserService';
angular.module('app').factory(serviceId, ['common', 'datacontext', currentUserService]);
function currentUserService(common, datacontext) {
var $q = common.$q;
var getLogFn = common.logger.getLogFn;
var logError = getLogFn(serviceId, "error");
var user = {};
var service = {
user: user,
doesUserHaveFeature: doesUserHaveFeature
};
activate();
return service;
function activate() {
var promises = [getCurrentUser()];
$q.all(promises);
}
function getCurrentUser() {
var deferred = $q.defer();
datacontext.getLoginInformation().then(function (data) {
user = data;
deferred.resolve(data);
});
return deferred.promise;
}
function doesUserHaveFeature(featureName) {
debugger;
var feature = featureName.toLowerCase();
var result = _.filter(user.features, function(item) {
var featureString = item.toLowerCase();
return feature == featureString;
});
if (result) {
return true;
}
return false;
}
}
})();
The service is injected into my Controller and my controller calls the doesUserHaveFeature() method.
However, the doesUserHaveFeature method is called before the promise in the activate method is resolved. Therefore, the user variable is still an empty object.
How can I ensure that the promise in the activate method is returned before the doesUserHaveFeature method is called?
Thanks!
Jeremy
As the user data is retrieved asynchronously, your factory methods are going to have to return promises. Here's how I'd do it...
.factory('currentUserService', function(datacontext) {
var userPromise = datacontext.getLoginInformation();
return {
user: userPromise,
doesUserHaveFeature: function(featureName) {
return userPromise.then(function(user) {
return _.some(user.features, function(feature) {
return feature.toLowerCase() === featureName.toLowerCase();
});
});
}
};
});
My Grails application doesn't receiving data from angularjs post request.
My AngularJS Controller is:
module.controller('MemberCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.submitForm = function () {
$http.post(uri + "receiveNewMember", $scope.member)
.success(function (data) {
console.log("Data Sent With Success! " + data);
})
.error(function (data) {
console.log("Fail");
});
};
}]);
My Grails Action is:
def receiveNewMember(){
render text: params.name
}
The Debugger Stops into action. But params variable hasn't any data but controller and action.
Someone knows how can I fix this?
The Post Data can be accessed via request.JSON in Grails Controller.
You can do something like this to emulate the way grails works:
post query parameters like jQuery
Also I created a Serializer factory to serialize any kind of javascript object to the expected way on grails:
(function() {
'use strict';
angular.module('app').factory('Serializer', function ($filter) {
function SerializerService(){}
var serializerService = new SerializerService();
serializerService.excludedProperties = ['$$hashKey'];
SerializerService.prototype.serialize = function(object){
var results = {};
this.serializeObject(results, object, "");
return results;
};
SerializerService.prototype.serializeObject = function(results, object, nameAtTheMoment){
if($.isArray(object)){
var array = object;
for (var i=0; i<object.length; i++){
var newNameAtTheMoment = nameAtTheMoment + "[" + i.toString() + "]";
this.serializeObject(results, array[i], newNameAtTheMoment)
}
}
else{
if(Object.prototype.toString.call( object ) === "[object Object]"){
var i=0;
for(var property in object){
if (object.hasOwnProperty(property) && this.excludedProperties.indexOf(property) == -1) {
var newNameAtTheMoment;
if(nameAtTheMoment !== "")
newNameAtTheMoment = nameAtTheMoment + "." + property;
else
newNameAtTheMoment = property;
this.serializeObject(results, object[property], newNameAtTheMoment);
i++;
}
}
}
else{ //the object is a simple value
if(Object.prototype.toString.call(object) === '[object Date]'){
var dateServerFormat = window.appConfig.dateServerFormat;
results[nameAtTheMoment] = $filter('date')(object, dateServerFormat);
}
else
results[nameAtTheMoment] = object;
}
}
};
return serializerService;
});
})();
And following the first link description you can do something like this:
angular.module('app', [...])
.config(function ($provide, $httpProvider) {
var serializer;
// Trick to inject dependencies on the config function.
$provide.factory('FactoryInjector', function () {
return {
setSerializer: function(serializerParam){
serializer = serializerParam;
}
};
});
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? $.param(serializer.serialize(data)) : data;
}];
})
.run(function ($rootScope, $state, $stateParams, Serializer, FactoryInjector) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
FactoryInjector.setSerializer(Serializer);
});
I have a factory which get data from server. In the factory method I have used $cacheFactory to cache getting data. My code is as follows..
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
return dataList;
}
else {
return $http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
return results.data;
});
}
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});
Now I have called GetBuyers method from controller. My method is like below..
var BuyerController = function ($scope, BuyersService) {
$scope.Buyers = [];
init();
function init() {
getBuyers();
}
function getBuyers() {
BuyersService.GetBuyers()
.then(function (data) {
$scope.Buyers = data;
}, function (error) {
alert(error.message);
});
}
};
app.register.controller('BuyersController', ['$scope', 'OMDataService', BuyerController]);
When I have executed my controller method second time I have got an error message in promise part.
Object doesn't support property or method 'then'
The issue here is that your function returns two different things: either a promise or plain data. To remedy this, use another promise to control the flow and return that one as the result of the function.
Update your code to
var buyersService = function ($http, $q,$cacheFactory) {
var serviceBase = '/api/OMData/';
var BuyersFactory = {};
buyersService.cache = $cacheFactory('cacheId');
BuyersFactory.GetBuyers = function () {
var buyersDataIsAvailable = $q.defer();
var dataList = buyersService.cache.get('BuyerData');
if (dataList != null && dataList.length > 0) {
buyersDataIsAvailable.resolve(dataList);
}
else {
$http.get(serviceBase + 'GetBuyers').then(
function (results) {
buyersService.cache.put("BuyerData", results.data);
buyersDataIsAvailable.resolve(results.data);
});
}
return buyersDataIsAvailable.promise;
}
app.factory('OMDataService', ['$http', '$q', '$cacheFactory', buyersService]);
});