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.
Related
I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});
I upgraded my angularjs package to 1.6.3 and found out that the .success and .error functions got deprecated are removed. Now after using .then and .catch, only the .catch executes. I'm struggling to find out why the request fails this time around.
My initial working code was:
if ($scope.IsDinamicReport) {
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
}).success(function (result) {
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
$('[data-table=container]')
.css('margin-left', '25px')
.css('padding-right', '25px')
.css('width', persentage)
.css('max-width', persentage);
}
else
alert("Error occured while generating the report, please contact helpdesk.");
}).error(function (data) {
alert("An error occured while generating the report, please try again.");
});
}
and then I changed it to the following:
if ($scope.IsDinamicReport) {
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
}).then(function (result) {
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
$('[data-table=container]')
.css('margin-left', '25px')
.css('padding-right', '25px')
.css('width', persentage)
.css('max-width', persentage);
}
else
alert("Error occured while generating the report, please contact helpdesk.");
}).catch(function (data) {
alert("An error occured while generating the report, please try again.");
});
}
How do I go about debugging what went wrong if you cannot see the error here already? The only thing I changed there is just the deprecated functions
Use the standard .then and .catch promise methods instead, but note that the method signatures and return values are different:
Before:
$http(...)
.success(function onSuccess(data, status, headers, config) {
// Handle success
//...
}).error(function onError(data, status, headers, config) {
// Handle error
//...
});
After:
$http(...)
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
return <some value>;
}).catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
throw <some error>;
});
For more information, see AngularJS Developer Guide - Migrating from 1.5 to 1.6
In the case of your code, the result value is a property of the response object:
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
//}).success(function (result) {
}).then(function (response) {
//RESULT is a property of response
var result = response.data;
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
use debugger; in your source code .
press F12 , F8 , F10 .it will help
From the angular doc the $http service return a promise that has two callback, of success and of failure (no catch method).
In your code you're trying to handle the rejection with a catch, but this is not reported in the doc.
This is the syntax provided, try to modify your code accordingly.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
source: https://docs.angularjs.org/api/ng/service/$http
i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}
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));
I've just started learning Angular.js. How do I re-write the following code in Angular.js?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Here's what I have so far -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
html
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Am I in the right direction?
In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.
So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
use $http:
AngularJS: API: $http
$http.post(url, data, [config]);
Implementation example:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
Lets break this down: Url is a little obvious, so we skip that...
data: This is the body content of your postman request
{
Description: 'Test Object',
TestType: 'PostTest'
}
config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});