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
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 am able to make REST API call using Postman/browser by passing Authorization token. However when I make the same call using AngularJS it's getting errored out. It's returning net::ERR_INSECURE_RESPONSE
I would like to know what can be possibly causing this error and how to fix this.
$http.get('https://hostname:8443/medrecdb-records', {
headers: {
'Authorization': 'Basic YWRtaW46UGFzc3dvcmQx' }})
.then(function (response) {
$scope.drug = response.data;
console.log("Response is: " + response);
}).catch(function (response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log("Response data is: " + data);
});
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.
I want to access to response successCallback(response)
var list_of_user = $http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.all_users = response.data;
}, function errorCallback(response) {
console.log(response);
});
console.log("$scope.all_users ", $scope.all_users)
is undefiend
I can access $scope.all_users from html, but how can I access to $scope.all_users in controller?
$http is async and console.log is executed before actually request is completed.
As you defined in comment that you want to compare two responses you can do that by simply putting a flag that will wait for both requests to finish.
var done = 0;
var onRequestFinishes = function() {
done += 1;
if (done < 2) {
return; // one of both request is not completed yet
}
// compare $scope.response1 with $scope.response2 here
}
and send first request and save response to $scope.response1 and invoke onRequestFinishes after that.
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response1 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
Similarly send second request
$http({
method: 'GET',
url: '/users/'
}).then(function successCallback(response) {
$scope.response2 = response.data;
onRequestFinishes();
}, function errorCallback(response) {
console.log(response);
});
For request handling you can create individual promise chains and use $q.all() to execute code when all promises are resolved.
var request1 = $http.get('/users/').then(function(response)
{
console.log('Users: ', response.data);
return response.data;
}
var request2 = $http.get('/others/').then(function(response)
{
console.log('Others: ', response.data);
return response.data;
}
$q.all([request1, request2]).then(function(users, others)
{
console.log('Both promises are resolved.');
//Handle data as needed
console.log(users);
console.log(others);
}
I have two $http posts that each post arrays of objects in a loop. The problem is that the second $http post is reliant on the first one completing. Is there a way to make them not async calls? I tried to used deferred but something is wrong in it as it is not working. It still fires group saving while tag saving is going on.
Angular:
var deferred = $q.defer();
var all = $q.all(deferred.promise);
for (var property in data.tagAdded) {
if (data.tagAdded.hasOwnProperty(property)) {
$http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: data.tagAdded[property].tag.Name })
}).success(function (response) {
deferred.resolve(response);
data.tagAdded[property].tag.Id = response.Data[0].Id;
data.tagAdded[property].tag.ProjectId = response.Data[0].ProjectId;
}).error(function (response) {
tagError = true;
$.jGrowl("Error saving new tags. Contact support.", { header: 'Error' });
});
}
}
deferred.promise.then(function() {
console.log(data);
});
all.then(function() {
groups.forEach(function(group) {
$http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).success(function(response) {
}).error(function(response) {
recError = true;
$.jGrowl("Error saving recruiting group. Contact support.", { header: 'Error' });
});
});
});
Going without promises is totally not what you want to do here. In fact, this is exactly the kind of situation where promises shine the most! Basically, you weren't using $q.all properly. You can just pass it a list of promises, and it will be resolved when they are all resolved. If any one of them fails, it will yield a rejected promise with the same rejection as the first one that failed. You can of course swallow that rejection via a .catch invocation that returns anything other than a $q.reject value.
I reimplemented what you had using promises. Both .success and .error are fairly limited, so I used the traditional .then and .catch methods here.
/**
* Here we define a function that takes a property, makes a POST request to
* create a tag for it, and then appends the promise for the request to a list
* called tagRequests.
*/
var tagRequests = [];
var createTag = function(property) {
tagRequests.push($http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: data.tagAdded[property].tag.Name })
}).then(function(response) {
var responseData = response.data;
data.tagAdded[property].tag.Id = responseData.Data[0].Id;
data.tagAdded[property].tag.ProjectId = responseData.Data[0].ProjectId;
return responseData;
}).catch(function (err) {
var errorMsg = "Error saving new tags. Contact support.";
$.jGrowl(errorMsg, { header: 'Error' });
// If we don't want the collective promise to fail on the error of any given
// tag creation request, the next line should be removed.
return $q.reject(errorMsg);
}));
};
/**
* We then iterate over each key in the data.tagAdded object and invoke the
* createTag function.
*/
for (var property in data.tagAdded) {
if (Object.prototype.hasOwnProperty.call(data.tagAdded, property)) {
createTag(property);
}
}
/**
* Once all tag requests succeed, we then map over the list of groups and
* transform them into promises of the request being made. This ultimately
* returns a promise that is resolved when all group POST requests succeed.
*/
$q.all(tagRequests)
.then(function(tagsCreated) {
return $q.all(groups.map(function(group) {
return $http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).then(function(response) {
return response.data;
})
.catch(function(err) {
var errorMsg = "Error saving recruiting group. Contact support.";
$.jGrowl(errorMsg, { header: 'Error' });
// If we want this collective promise to not fail when any one promise is
// rejected, the next line should be removed.
return $q.reject(errorMsg);
});
}));
});
I highly suggest brushing up on Promises in general, and then taking another look at the $q documentation. I've also written this blog post on the way promises work in Angular and how they differ from most promise implementations.
This is exactly what promises do. Angular uses Kris Kowal's Q Library for promises. Check out the Angular docs page, has a perfect example of the promise pattern. Basically you would do the first call, then once it's promise returns success, make the second call.
I had to alter my code a bit, and get some coworker team work. I went completely without promises.
I use a counter to track when counter = 0 by adding to the counter then upon success/fail i decrement from the counter taking it backwards for each completed transaction. When counter is at 0 I am done then call my next bit $http post.
Angular Deferred:
var counter = 0;
var tags = [];
for (var property in data.tagAdded) {
if (data.tagAdded.hasOwnProperty(property)) {
tags.push({ Name: property });
}
}
if (tags.length == 0) {
groupInsert();
} else {
tags.forEach(function (tag) {
counter ++;
$http({
method: "POST",
url: '/api/projects/' + data.Project.Id + '/tags',
data: ({ Name: tag.Name })
}).success(function (response) {
console.log(response)
counter--;
data.tagAdded[property].tag.Id = response.Data[0].Id;
data.tagAdded[property].tag.ProjectId = response.Data[0].ProjectId;
if (counter == 0) {
groupInsert();
}
}).error(function (response) {
counter--;
tagError = true;
$.jGrowl("Error saving new tags. Contact support.", { header: 'Error' });
if (counter == 0) {
groupInsert();
}
});
});
}
function groupInsert() {
groups.forEach(function (group) {
console.log(group)
$http({
headers: { 'Content-Type': 'application/json; charset=utf-8' },
method: "POST",
url: '/api/projects/' + data.Project.Id + '/recruiting-groups',
data: angular.toJson(group, false)
}).success(function (response) {
}).error(function (response) {
recError = true;
$.jGrowl("Error saving recruiting group. Contact support.", { header: 'Error' });
});
});
}