Javascript function return undefined - javascript

I've an AngularJS project and there the is a get request is made to the backend like this which will return the data and this function is used because the get request to the same url is made multiple times
function getfunction(some input data) {
$http.get('requset URL' , { params : {some parameters})
.success(function(data){
return data;
});
}
var output = getfunction(input data to the function);
However the output is always undefined how can I fix it so the output will have the values returned from the above get request.

$http returns a promise. Your data will arrive asynchronously.
function getfunction(some input data) {
return $http.get('requset URL' , { params : {some parameters});
}
var output;
getfunction(input data to the function).then(function(data){
output = data;
}, function(){
// Handle errors.
});

$http.get uses promises. Or in other words: it does the request asynchronously.
You can return what $http.get returns itself - a promise - and add a continuation using then:
function getfunction(some input data) {
return $http.get('requset URL' , { params : {some parameters});
}
getfunction(input data to the function).then(function(data) {
});
// or .success
getfunction(input data to the function).success(function(data) {
});

The call is asynchronous, so the function you are calling will run first and then the success callback will run when the response is returned from your get request. The success handler should be what handles the output in this scenario (e.g showing the return value in a textbox)

$http return $promise. so either you use $q service :
function getfunction(some input data) {
var deferred = $q.defer();
$http.get('requset URL' , { params : {some parameters})
.success(function(data){
deferred.resolve(data)
});
return deferred.promise;
}
var output = getfunction(input data to the function).then(function(data){
output = data;
}, function(err){
console.log(err)
});
or
function getfunction(some input data) {
return $http.get('requset URL' , { params : {some parameters});
}
var output;
getfunction(input data to the function).then(function(data){
output = data;
}, function(err){
console.log(err)
});

Related

Promise returning before $http promise concludes

I need to have one function call a second function where the second function includes some setup code, an http callback to a REST server and then finely some cleanup code before returning to the first function. The idea is to have the first function then displays a result message after the second function is finished.
The following example returns from the second function before it finishes the callback so I don't get the results of the http success or error.
var saveData = function(_this){
return new Promise(function(resolve,reject){
resolve( _this.Save('SavExit') );
});
};
saveData(this).then(function(httpResponse){
// display response after http callback finishes
console.log(httpResponse);
});
this.Save = function (lcAction) {
// validate data
$http.post('serverCallback.aspx',oSelectedVendor).
success(function (data, status, headers, config) {
// process data before returning;
return true;
}).
error(function(data,status,headers,config){
console.log(data);
return false;
});
};
You need to return Promise from the Save method:
this.Save = function (lcAction) {
// validate data
return $http.post('serverCallback.aspx',oSelectedVendor).
success(function (data, status, headers, config) {
// process data before returning;
return true;
}).
error(function(data,status,headers,config){
console.log(data);
return false;
});
};
Note return I added in front of $http.
In addition, since you return Promise from Save, you don't need another one in saveData:
var saveData = function(_this) {
return _this.Save('SavExit')
};

Angular Http put method giving error while passing data (server expecting form param )

I am trying to use the http put method to pass some data on server and server is looking for form param in put method.
var deferred = $q.defer();
$http({
method: 'PUT',
url: 'http.hello.com/rest/sample/'+fileName,
data: {status: status}
}).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject(data);
});
return deferred.promise;
but server still giving missing data custom error then how can I pass the data in put method.
also try $.param() but it convert the data into string that's not correct
First of all $http itself returns a promise, so you do not need to $q
To pass the data in a neater way you can use the following
'use strict';
(function() {
function AppService($http) {
var AppService = {
putStatus(status, filename) {
return $http.put('http.hello.com/rest/sample/'+filename, {status: status})
}
};
return AppService;
}
angular.module('app')
.factory('AppService', AppService);
})();
Use as follows (somewhere in the controller)
AppService.putStatus(status, filename)
.then((response) => {
// do something on success
})
.catch((err) => {
//if error occured
});

How to get response from service on controller

I'm trying to separate the $http.post() call into a ".factory()", But would like to fetch the response which is coming async on the controller. Is there a way of doing that?
Controller:
Login.post($scope.user);
Factory:
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
There is a .then() but I want that on the controller, so I can behave accordingly. Thank you!
Basically you need to return the $http.post promise, and from success function you could return a data that will return to the consumer of this method. So that you could easily call the factory method from controller & inside .then function of that call you could have success and error function.
Code
.factory('Login', function($http, SERVERURL) {
var serverUrl = SERVERURL;
return {
'post': function(user) {
return $http.post(serverUrl + '/login', user).
then(function(response) {
console.log(response);
return response.data; //return data from here
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
Controller
Login.post().then(function(data){ //success function
console.log(data)
}, function(error){ //error function
console.log(error);
})
You could add a callback param.
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user, callback){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
callback(null, response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
callback(response);
});
}
};
})
And your controller will become:
Login.post($scope.user, function(err, response) {
if(err) {} //do something if there is an error
// or deal with the response
});
To return any response to controller just do:
return {
'post' : function(user){
return $http.post(serverUrl+'/login', user);
}
};
In your controller you will already call.then()
Angular's $http methods return a Promise.
The $http API is based on the deferred/promise APIs exposed by the $q service.
Factory
Your method post is not yet returning anything but can quite simply return the Promise which is created by calling $http.post:
.factory('Login' , function($http, SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function (user) {
return $http.post(serverUrl + '/login', user)
// ^^^^^^
.then(function (response) {
console.log(response);
return response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
});
Controller
Then consume the result of the returned Promise by calling then on it:
Login.post($scope.user).then(function (res) {
// do something with `res`...
});

AngularJS - return promise success value to the calling function

I am learning AngularJS and AJAX.I am trying to assign the data being returned by the success function to user. grantRole belongs to Auth service. The value of user as I currently have it is a promise. How do I assign the returned data on success to user?
$scope.grantRole = function(user) {
user = Auth.grantRole(user).then(
function success(data){
return data;
},
function error(err){
console.log(err);
}
);
grantRole: function(user,callback) {
var cb = callback || angular.noop;
var data = {id: user._id,controller:'role'};
return User.update({id: user._id,controller:'role'},data,
function(user) {
return cb(user);
}, function(err) {
return cb(err);
}).$promise;
};
The current value of user being a promise is correct. Once the promise gets resolved, it will be assigned to the data returned on success.
But you have to be careful when reassigning objects or arrays. See Service variable not updating in controller
E.g., don't do this: user = ...;
Rather, do this: angular.copy(newInfo, user) or this: user.email = ...
$scope.grantRole = function(user) {
Auth.grantRole(user).then(
function success(data){
angular.copy(data, user);
},
function error(err){
console.log(err);
}
);

angular, correct way for a function callback

I am writing an ItemProvider for my app in angular js.
I chose a service.
app.factory('ItemProvider', function($http) {
var url = "http://localhost:7888/api.php/json?";
return {
get_data: function() {
$http.get(url).
success(function(data,status,headers,config) {
json = data;
console.log("app returned ok");
console.log(json);
callback(json);
}).
error(function(data,status,headers,config) {
console.log("Error getting data from app!");
json = data;
callback(json);
});
callback = function(json) {
console.log("callback");
return json;
}
console.log("already done");
}
};
});
Of course what happens here is that get_data returns immediately before the actual calls to the backend via $http returned...
How do I correctly have a get_data function which will return the data from the backend? I tried adding a callback (see code above) but I realize by the time it's getting called, get_data already finished as well...
$http is hardcoded to only work asynchronously, meaning your only option is to code with that in mind. Due to this, it isn't possible for get_data to directly return the data, instead, it has to either accept a callback, or return a promise. The promise route is far easier in my opinion.
app.factory('ItemProvider', function($http) {
var url = "http://localhost:7888/api.php/json?";
return {
get_data: function(url) {
return $http.get(url);
}
};
});
example usage:
//...
ItemProvider.get_data('/items')
.success(function (items) {
console.log(items);
})
.error(function () {...});
//...

Categories

Resources