Angularjs $http then function - angularjs

I've created a JS Object with a method that calls a $http to retrieve a value, but when the $http is done I want to assign this value to a property, I can't seem to be able to get this value:
the property this.user always ends up with the promise itself, but I want to assign the value returned from the XHR Request or undefined on failure, I think this is a context problem, I just don't know how to fix it
var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
this.numint = numint;
this.company_id = company_id;
this.user_id = user_id;
this.title = title;
this.description = description;
this.priority = priority;
this.status = status;
this.assignation = assignation;
this.created_at = created_at;
this.user = undefined;
this.getUser = function() {
if(this.user_id === undefined)
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
this.user = http
.then(
function(data) {
return data;
}
,
function() {
return undefined;
});
return http;
}
};

var http is a promise object because the return value of Angular's $http service is a promise (docs). Use .then() to get the return value once the AJAX request has returned and the promise has resolved.
var self = this;
http.then(function (data) {
self.user = data;
});

var Ticket = function(numint, company_id, user_id, title, description, priority, status, assignation, created_at) {
var self = this; // new code
self.numint = numint; //use self inseat
self.company_id = company_id;
this.getUser = function() {
if(self.user_id === undefined) // you had one preblem here, because "this" here is direrent to the this.user_id you neded, so use self
return false;
var http =
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
self.user = data
;},
function () {
self.user= undefined;
});
}
};

assign this to a different value OR! or us .bind.
$http({
method : 'GET',
url : '/users/' + this.user_id,
timeout : 100000,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (data){
this.user = data;
}.bind(this));

Related

How to use $scope in $http url

When I log the id it shows me the correct id. I want to pass this id in the second url and fetch data accordingly.
Like when the id is 9 and when i put it like this url: &room_type=9&day=1 it works but not when I use it this way url: '&room_type=' +$scope.id + '&day=1'
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
});
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response){
var plan = response.data;
$scope.plan = plan;
});
Its because the way async programming works in javascript. In your code you are calling these 2 http calls back to back and the defined callback (then) does not fire until later when you get a result. So id will not be populated at the time your 2nd http call is fired. If you want to call this with id and id is defined in the callback of your 1st call then you have to call it from inside the callback of your first http call, not after it.
Here is how you could handle it
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
// call http now that id is defined
$http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1'
}).then(function(response2){
var plan = response2.data;
$scope.plan = plan;
});
});
Http request you make works async, use promise chains to call the request after another
function getHotelId(){
return $http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
})
}
function getPlan(){
return $http({
method:'GET',
url: '&room_type=' +$scope.id + '&day=1',
})
}
$scope.processform = function() {
getHotelId()
.then( function( response )
{
var roomdata = response.data;
$scope.roomdata = roomdata;
var roomtype = roomdata.data;
angular.forEach(roomtype, function(value, key){
var id = value.room_type_id;
$scope.id = id;
console.info(id);
});
return getPlan();
})
.then(function(response){
console.log(response.data);
})
}

Spring & AngularJS : Undefined status for PUT method

i am returning a string on updation of a record and want to show the same string on UI(updated successfully)
Here is my code :
#RequestMapping(method = RequestMethod.PUT, value = "/update")
public #ResponseBody String update(#RequestParam("id") int id, #RequestParam("name") String name) {
employeeService.update(id, name);
return "updated successfully";
front end code :
$scope.update = function(Employee) {
$http({
method : 'PUT',
url : '/Employee/update',
params : {
id : Employee.id,
name : Employee.name
}
}).success(function(data, status, headers, config) {
$scope.updatedText = data;
$scope.updatedFlag = true;
}).error(function(data, status, headers, config) {
console.log("data.token " + data.token);
});
};
Here are two interesting screen shots
here status is undefined
again
here status is 200
please let me know what is the reason behind that and yes i can see that there is a change in the hibernate table
Please help
Well i'll leave you an example how i handle calls to the API with $http and promises $q
i use it inside a service, that can be injected on my controllers.
this.update = function (Employee) {
var datosRecu = null;
var deferred = $q.defer();
var token = $cookies.getObject('token');
$http({
url: '/Employee/update',
method: 'PUT',
params: {
id: Employee.id,
name: Employee.name
},
headers: {
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
return deferred.promise;
};
now when i inject it on my controller i can read the promise deferred.promise with all the data of response.
i hope it help you.

return data inside function from http post

I want to get data pass from a function, the data successfully return inside the success response. However I can't return the data from the function itself.
function getStatusPublished(dating, product)
{
var datas = "";
var success = function(response, status, headers, config){
datas = response;
}
var error = function(error, status, headers, config){
datas = "error";
}
var cdnss = "htttp://application_ajax";
$http.post(cdnss+"&pblishDateVacan="+dating+"&ProjectID="+product)
.success(success).error(error);
console.log(datas);
}
In the console.log, it just said undefined.
Please help. Thanks.
The $http.post method returns a promise; not data.
To return a promise, simply use a return statement.
function getStatusPublished(dating, product) {
var url = "htttp://application_ajax";
var postData = {};
var params = {
pblishDataVacan: dating,
ProjectId: product
};
var config = { params: params };
var promise = $http.post(url,postData,config);
//return promise
return promise;
}
To get the data from the promise, use the .then method:
var promise = getStatusPublished(d, p);
promise.then( function(response) {
$scope.data = response.data;
return response.data;
}).catch ( function(response) {
console.log(response.status);
throw response;
});

How to update controller variable in service angularJS

This is my controller.
sampleApp.controller('SupplierController', ['$scope', '$http', 'SupplierService', function ($scope, $http, SupplierService){
$scope.Suppliers = [];
$scope.getSuppliers = function() {
SupplierService.getSuppliers().then(function(data) {
$scope.Suppliers = data;
});
};
$scope.editSupplier = function(supplier) {
SupplierService.editSupplier(supplier);
editMode = false;
};
$scope.getSuppliers();
}]);
This is my service.
sampleApp.factory('SupplierService', function($http, $q) {
var SupplierService = {};
var SupplierList = [];
SupplierService.getSuppliers = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( SupplierList.length === 0 )
{
return $http(req).then(function (response) {
SupplierList = response.data
return response.data;
});
}
else
{
var deferred = $q.defer();
deferred.resolve(SupplierList);
return deferred.promise;
}
};
SupplierService.addNewSupplier = function(supplier) {
var Info = {};
Info.Action = "ADD";
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
SupplierService.editSupplier = function(supplier) {
var Info = {};
Info.Action = "UPDATE";
Info.SupplierID = supplier.id;
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
return SupplierService;
});
What i want is, only when http call for editSupplier is successful then only i want this line to be executed.
editMode = false;
Currently above line is in $scope.editSupplier function. so irrespective of success or failure it is getting called. How to move this line to service??
Any better approach will be highly appreciated.
The easiest way, based on your current setup, would be to return $http(req) (as that is a promise). So the end of editSupplier would say:
return $http(req);
And in your controller, you could do:
SupplierService.editSupplier(supplier).success(function(response) {
editMode = false;
});
You could additionally chain the .error handler if you have something specific to do in the case of an error.
#tandrewnichols stole my initial answer so I'll offer the alternative.:p
Move editMode into the service and use a getter to check the value of editMode.
Also, are you intending to make editMode a global variable in your application?

how to write controller for this service?

myapp.factory('serviceName', function( $http, webStorage){
var factory = {};
var resoureurlBase=some base url;
factory.genericService = function(method, payload, methodName, callbackFn, callbackError, param) {
var httpRequest = null;
if (param && param == true) {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
params: payload,
headers: {
'Content-Type': 'application/json'
}
});
} else {
httpRequest = $http({
url: resoureurlBase+methodName,
method: method,
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
httpRequest.then(function(response) {
if (callbackFn && callbackFn.call) {
callbackFn.call(null, response);
}
},
function(response) {
if (callbackError && callbackError.call) {
callbackError.call(response);
}
});
httpRequest.error(function(data, status, headers, config) {
});
};
return factory;
});
/*
I have written service like above how can i handle in controller
i mean
how to write call back function in controller
how to inject
etc..
*/
Simple DI(dependency injection) it into your controller:-
myapp.controller('myCtrl',['$scope','serviceName',function($scope,serviceName){
// use serviceName to call your factory function
}]);
Ref:- https://docs.angularjs.org/guide/di
You need to call service like
serviceName.genericService(--parmas--).then(function(d){
//success
})
because from service serviceName, you're returning a promise that need to resolved using .then only.
Controller
var mainController = function($scope, serviceName) {
var callbackFn = function() {
console.log('Success');
}
var callbackError = function() {
console.log('Error');
}
var parameter = {
param1: 1
},
method = 'something', payload = 100, methodName = 'something';
serviceName.genericService(method, payload, methodName, callbackFn, callbackError, parameter).then(
//success function
function(data) {
//call after call succeed
},
//error function
function(error) {
//call after call error
});
};
myapp.controller('mainController', ['$scope', 'serviceName', mainController()];
Hope this could help you. Thanks.

Resources