I realize this is a very similar question to this one. But I'm still unclear on how to do it in my situation. Just need some help with a successful callback.
This is what works:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(log);
}
function log(response) {
logger.debug(response);
return response;
}
This is what I want to accomplish:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(log(response, logMessage);
}
function log(response, logMessage) {
logger.debug(logMessage, response);
return response;
}
You can use this:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(
function success(response) {
return log(response, logMessage);
}
);
}
Depending on your preference/requirements you could do a few things. I normally write promise callbacks like this, so you could do:
.then(function success(response){
return log(response, logMessage);
});
or, depending on how you feel about this way (i know some people don't like it, i try to avoid unless absoluley nessesary)
.then(log.bind(null, response, logMessage));
Do either of these work for you?
See if it can help you:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
var deferred = $q.defer();
return $http.post(GetStuff, { custId: accountNumber })
.success(function(response){
deferred.resolve(response);
log(response, logMessage);
}).error(function(){
deferred.reject();
})
return deferred.promise;
}
Related
I have the function below that sends a fetch request and return a JSON result, I have checked the response and it does return a value that I need, return userid does return me a value, the problem is when I call this function it returns an undefined value even though I have checked it does return a value with the function.
I am looking for a simple solution.
function currentloginid() {
fetch('http://localhost/gaq/api/api.php?action=userid', {
method: 'GET',
}
)
.then(function(response) {
response.json().then(function(data) {
var userid = JSON.parse(data);
console.log(userid);
return userid;
})
})
}
You need to return the response.json() output as well. Adding this return should allow you to get the value. If you want to avoid using it in the .then function, you should look into async/await
function currentloginid() {
return fetch('http://localhost/gaq/api/api.php?action=userid', {
method: 'GET',
})
.then(function(response) {
return response.json()
})
.then(function(data) {
var userid = data;
console.log(userid);
return userid;
})
.catch(err){
//Do some error handling
}
}
currentloginid().then(function(id) {
//Do something with it
})
I updated Angular to version 1.6.4.
So I had to update .success and .error to .then
Now I get the following error:
TypeError: .getAll(...).then is not a function
The Problem is here in the service:
function getAll(page, size) {
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000}).then(function (response) {
data = response;
}), (function(response) {
alertService.setAlert({'message': 'jobmatch.server.unavailable', 'classified': 'danger', 'lives':1});
});
}
Here is the controller:
if($cookies.get("authenticated")=='true'){
//get a list of all candidateprofiles with the use of a page and a size
candidateprofilesService.getAll($scope.page, $scope.size).then(function() {
$scope.data = candidateprofilesService.getData()._embedded.candidateprofiles;
candidateprofilesService.getAll($scope.page, $scope.size+10).then(function() {
if(candidateprofilesService.getData()._embedded.candidateprofiles.length > $scope.data.length){
$scope.moreData = true;
}
else {
$scope.moreData = false;
}
})
});
}
You service code should be like :
myApp.service('candidateprofilesService', function($http) {
this.getAll = function (page, size) {
// just return the promise , don't evaluate here
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000});
}
this.getData = function(){
// your getData() method body, also just return the promise.
}
});
Then in your controller after injecting service,
candidateprofilesService.getAll($scope.page, $scope.size).then(function(response){
//Evaluate promise here and handle the response
}, function(error){
//handle error
});
Your function should be like this,
function getAll(page, size) {
return $http.get(baseUrl + '/jobprofiles?page='+page+'&size='+size, {timeout: 5000}).then(function (response) {
return data = response;
}, function(response) {
alertService.setAlert({'message': 'jobmatch.server.unavailable', 'classified': 'danger', 'lives':1});
});
}
function get (id, ignore) {
var deferred = $q.defer();
$http.get('v1/info/' + id, {
ignoreAuthModule: ignore
})
.success(function (data) {
deferred.resolve(data.data);
})
.error(function (reason) {
deferred.reject(reason.message););
});
return deferred.promise;
}
init();
function init(){
users.get($routeParams.id)
.then(function (data) {
if(data.has_something === 1){
$scope.hasSomething = true;
}else{
$scope.hasSomething = false;
}
});
}
I have a Service that get the information about user using promise and Fetching information from the service with init function
//if i call init function this should call two times one from function initialization and other i'm calling it from service
how can i stop two times calling api I mean it should call one time if already called
You're using the explicit promise creation antipattern here, and your code could be much simpler. Here is how you can use memoization to avoid requesting the same user twice:
.factory('users', ['$http', function ($http) {
var userPromises = {};
function get (id, ignore) {
if (!userPromises[id]) {
userPromises[id] = $http.get('v1/info/' + id, {
ignoreAuthModule: ignore
})
.then(function (data) {
return data.data;
})
.catch(function (reason) {
throw new Error(reason.message);
});
}
return userPromises[id];
}
return {
get: get
};
});
You can assign your deferred.promise to some variable and then return that variable, and before your http call just check whether that variable is already defined or not
function get (id, ignore) {
if (angular.isUndefined(user)) {
var deferred = $q.defer();
$http.get('v1/info/' + id, {
ignoreAuthModule: ignore
}).then(function(response) {
if (response.status == 200) {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
};
user = deferred.promise;
return user;
} else {
return user;
}
}
This way your api will get called only once.
I was wondering how I could check wether or not a function was successfull or had an error. I check for this in the function itself. but how can I recheck the result when calling the service.
I've tried something like this
entryService.update($scope.entry)
.success(function(){
$scope.entry = data;
$state.go('entry', {id: $scope.entry._id});
}).error(function(){
error = true;
});
This however doesn't work. And I was wondering how to get a similar result?
My service funtion looks like this:
angular.module('academiaUnitateApp')
.factory('entryService',function($http){
var service = {};
service.update = function(entry, callback){
$http.put('/api/entrys/' + entry._id, entry)
.success(callback, function(data){
console.log('Updated entry : ', data);
})
.error(callback, function(error){
console.log("Couldn't update entry. Error : ", error);
});
};
return service;
});
You can return true or false from the function for success or failure.
Check comments on code
entryService.update($scope.entry)
.success(function(){
$scope.entry = data;
$state.go('entry', {id: $scope.entry._id});
}).error(function(){
error = true;
});
angular.module('academiaUnitateApp')
.factory('entryService',function($http){
var service = {};
service.update = function(entry, callback){
$http.put('/api/entrys/' + entry._id, entry)
.success(callback, function(data){
console.log('Updated entry : ', data);
})
.error(callback, function(error){
console.log("Couldn't update entry. Error : ", error);
//IF ERROR, RETURN NULL
return null;
});
//MUST RETURN DATA HERE TO ALLOW .SUCCESS TO RUN
return data;
};
return service;
});
The return data in Update function, will make the success ( or .done) function to be called.
The following snippet returns the following error: TypeError: object is not a function
service.deleteItem = function(itemId) {
var def = $q.defer();
$http.delete(SERVER_REST_PATH + '/items/' + itemId)
.success(function() {
def.resolve();
}).error(function(data, status) {
def.reject("Error deleting the item");
});
return def.promise();
};
If I rewrite it as the following it works:
service.deleteItem = function(itemId) {
return $http.delete(SERVER_REST_PATH + '/items/' + itemId);
};
All other $http methods that I use(i.e GET, PUT, POST) in my app are wrapped with the $q the same way and they don't have this issue. Only the DELETE is causing this issue. When I debug it it just skips the $http's success(), error() and then() methods. I'm using angular version 1.3.13.
change return def.promise(); to return def.promise;
example :
function deferredTimer(success) {
var deferred = $q.defer();
$timeout(function() {
if (success) {
deferred.resolve({ message: "This is great!" });
} else {
deferred.reject({ message: "Really bad" });
}
}, 1000);
return deferred.promise;
}