AngularJS Http Post - 500 Internal Server Error - javascript

I know there's a lot of other 500 (Internal Server Error) questions out there, but reading them is still not helping my case.
I am working on two angularjs methods that have $http post calls in them.
FIRST PROBLEM
The first successfully hits the server-side controller, and returns a JSON object as I expect it, but my drop downs are not being filled by the result of the factory call.
One thing that concerns me, is the console output. (As you'll see in the code below I have several print statements.) The URL is printed, and then my drop down options field is printed as undefined, and then the response from the server comes back with the response. Do I need to tell the JS to wait for the response? Some sort of ASYNC?
SECOND PROBLEM
I have the exact same http post method call (but with new variables), and I get the 500 (Internal Server Error) error message. The server-side ctrl method is not being hit for this call (based on break point in ctrl).
Questions
How do I fill my drop down successfully with the result of the
$http.post call?
Why is my second $http.post method creating the 500 (Internal Server Error)?
Javascript
'use strict';
var app = angular.module('LineModule', ['ngMaterial']);
app.controller("LineCtrl", ['$scope', '$http', 'LineService',
function ($scope, $http, LineService) {
$scope.Types = LineService.get_DropDownList("Type");
console.log("Types:"); console.log($scope.Types);
$scope.Statuses = LineService.get_DropDownList("Status");
$scope.FundingSources = LineService.get_DropDownList("Funding_Source");
...
$scope.get_DeptLeader = function () {
$scope.SelectedLeader = LineService.get_DeptLeader($scope.CPOC_Title, $scope.CostCenter_ID);
};
}]);
app.factory('LineService', ["$http", function ($http) {
return {
...
***FIRST METHOD***
get_DropDownList: function (field) {
var info = {
section: 'Line',
field: field
};
var URL = getBaseURL() + 'DBO/DropDown_GetList';
console.log(URL);
var DropDown;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DropDown = response.data;
console.log(DropDown);
return DropDown;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
***SECOND METHOD***
get_DeptLeader: function (CPOC_Title, CostCenter_ID) {
console.log("call get leader");
if (CPOC_Title < 1 || CPOC_Title == undefined) { return "No Title Selected"; }
if (CostCenter_ID < 1 || CostCenter_ID == undefined) { return "No Cost Center Selected"; }
console.log(CPOC_Title);
console.log(CostCenter_ID);
var info = {
Leader_ID: CPOC_Title,
CostCenter_ID: CostCenter_ID
};
var URL = getBaseURL() + 'DBO/DeptLeader_GetCurrent';
console.log(URL);
var DeptLeaders;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DeptLeaders = response.data;
console.log(DeptLeaders);
return DeptLeaders;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
};
}]);
DBO Controller: Server-Side
[HttpPost]
public JsonResult DeptLeader_GetCurrent(string Leader_ID, string CostCenter_ID)
{
try {
List<SelectListItem> DL = DB.DeptLeader_GetByIDs(Leader_ID, CostCenter_ID);
return Json(DL, JsonRequestBehavior.AllowGet);
}
catch (Exception e){
string error = e.ToString();
return null;
}
}
[HttpPost]
public JsonResult DropDown_GetList(Sections section, DropDownFields field)
{
return Json(DB.GetDropDownValues(section, field), JsonRequestBehavior.AllowGet);
}
CSHTML
<div ng-app="LineModule" ng-controller="LineCtrl" class="container col-md-12">
...
<select ng-model="Type_ID" class="form-control" required>
<option ng-value="T.Value" ng-repeat="T in Types">{{T.Text}}</option>
</select>
...
<select ng-model="CPOC_Title" class="form-control" ng-change="get_DeptLeader()">
<option ng-value="D.Value" ng-repeat="D in DeptLeaders">{{D.Text}}</option>
</select>
{{SelectedLeader}}
...
</div>

Related

User is not defined Angular js

i have a problem when i click in the button it give me an error that user is not defined
i don't know what the problem
<input type="button" class="btn btn-danger" value="Active"
ng-click="Active(User)" />
this is my function in page Controller Asp MVC :
public string Active(AspNetUser User)
{
if (User == null) return "User Not Updated! Try Again";
var userToUpdate = db.AspNetUsers.Where(x => x.Id == User.Id).FirstOrDefault();
if (userToUpdate == null) return "User Not Found.";
if (userToUpdate.IsActive == true)
{
userToUpdate.IsActive = false;
}
else
{
if (userToUpdate.IsActive == false)
{
userToUpdate.IsActive = true;
}
db.SaveChanges();
return "User successfully Changed";
}
return "User already changed";
}
and this is my Script :
$scope.Active = function() {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
datatype: "json",
data: JSON.stringify(User)
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};
You are not passing anything to the function $scope.Active. Pass the User:
$scope.Active = function(User) {...}
The datatype property is ignored by the AngularJS framework. Also it is not necessary to stringify JavaScript objects. The AngularJS framework does that automatically.
$scope.Active = function(user) {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
̶d̶a̶t̶a̶:̶ ̶J̶S̶O̶N̶.̶s̶t̶r̶i̶n̶g̶i̶f̶y̶(̶U̶s̶e̶r̶)̶
data: user
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};
For more information, see
AngularJS $http Service API Reference

Dropdownlist is not setting values using angular JS

I have a requirement where I want to bind dropdownlist using MVC and angular JS.
I tried like below
var app1 = angular.module('Assign', [])
app1.controller('SAPExecutive_R4GState', function ($scope, $http, $window) {
// alert(UMSLocationDetails);
var LocObj = JSON.parse(UMSLocationDetails)
var ZoneValue = "";
$.each(LocObj, function (index, element) {
ZoneValue += element.LocationID + ",";
});
ZoneValue = ZoneValue.substr(0, ZoneValue.length - 1);
var Values = { "MaintZones": ZoneValue };
alert(JSON.stringify(Values));
$scope.DefaultLabel = "Loading.....";
$http({
method: "POST",
url: "/App/GetR4GStates",
dataType: 'json',
data: JSON.stringify(Values),
headers: { "Content-Type": "application/json" }
}).success(function (result) {
$scope.DefaultLabel = "--Select--";
$scope.State = data;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
});
<select id="SAPExecutive_R4GState" class="form-control" ng-model="R4GState.Selected" ng-controller="SAPExecutive_R4GState as R4GState" ng-init="Select" ng-options="b for b in list">
</select>
And my CS code
[HttpPost]
public JsonResult GetR4GStates(string MaintZones)
{
List<SelectListItem> lstR4GState = new List<SelectListItem>();
try
{
Filters ObjFilter = new Filters();
DataTable dt = ObjFilter.GetR4GState(MaintZones);
if (dt.Rows.Count > 0)
{
lstR4GState = (from DataRow dr in dt.Rows
select new SelectListItem()
{
Text = Convert.ToString(dr["R4GSTATENAME"]),
Value = Convert.ToString(dr["R4GSTATECODE"])
}).ToList();
}
else
{
SelectListItem slEmptyData = new SelectListItem();
slEmptyData.Text = "No Data found";
slEmptyData.Value = "No Data found";
lstR4GState.Add(slEmptyData);
}
}
catch (Exception e)
{
}
// ErrorLog.HandleErrorLog("", "", "GetR4GStates", "Error2");
return Json(lstR4GState);
}
I am getting values in return Json(lstR4GState); but the values are not getting set in the dropdown.
Please suggest where I am going wrong as I am new to angular
It is recommended to user THEN and CATCH in AngularJS > 1.5
This should work:
angular.module('Assign', [])
.controller('SAPExecutive_R4GState', function($scope, $http, $window) {
const payload = {};
$http.get('https://dog.ceo/api/breeds/list/all', payload)
.then(function(response) {
// Please be aware RESPONSE contains the whole response.
// You probably want RESPONSE.DATA
console.log(response.data);
})
.catch(function(err) {
// do something with err message });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Assign" ng-controller="SAPExecutive_R4GState"></div>
Please note this example uses a GET request, just so i could show it works,
in a GET request, the payload will be added as querystring
If you change it to $http.post, the payload will be added into the body of the request.

is it possible not to execute the promise (.then ()) in the controller when there is an error in a web request?

I'm currently using a factory called http that when I invoke it, I make a web request. this receives as a parameter the url of the web request.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(data) {
oHttp.data=data.data;
},function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
function HelloCtrl($scope, http) {
http.getData('https://www.reddit.com/.json1').then(function(){
if(http.data!=undefined){
console.log(http.data)
}
})
}
I would like the promise not to be executed on the controller if the result of the web request is not satisfied or there is a problem. is there any better solution? I want to avoid doing this every time I make a web request, or do not know if it is the best way (see the if):
//I am putting "1" to the end of the url to generate an error.
http.getData('https://www.reddit.com/.json1').then(function(){
//validate that the result of the request != undefined
if(http.data!=undefined){
alert(http.data.kind)
}
})
In my real project I make n web requests using my factory http, I do not want to do this validation always. I do not know if I always have to do it or there is another solution.
this is my code:
https://plnkr.co/edit/8ZqsgcUIzLAaI9Vd2awR?p=preview
In rejection handlers it is important to re-throw the error response. Otherwise the rejected promise is converted to a successful promise:
app.factory('http', function ($http) {
var oHttp= {};
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(response) {
̶o̶H̶t̶t̶p̶.̶d̶a̶t̶a̶=̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
return response.data;
},function(response) {
alert("problem, can you trying later please?")
//IMPORTANT re-throw error
throw response;
});
}
return oHttp;
});
In the controller:
http.getData('https://www.reddit.com/.json1')
.then(function(data){
console(data)
}).catch(response) {
console.log("ERROR: ", response.status);
});
For more information, see You're Missing the Point of Promises.
In Service
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function () {
return $http({
method: 'GET',
url: 'https://www.reddit.com/.json1'
});
}
return oHttp;
});
In controller
function HelloCtrl($scope, http) {
var httpPromise = http.getData();
httpPromise.then(function(response){
console.log(response);
});
httpPromise.error(function(){
})
}
So I tried this in codepen having ripped your code out of plinkr
https://codepen.io/PocketNinjaDesign/pen/oGOeYe
The code wouldn't work at all...But I changed the function HelloCtrl to a controller and it seemed happier....?
I also set response.data to default to an empty object as well. So that way if you're populating the data in the page it will be empty if nothing arrived. You can then in some instances on the site check the length if it's really required.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.data = {};
oHttp.getData= function (url) {
var config = {
method: 'GET',
url: url
}
return $http(config).then(function(response) {
oHttp.data = response.data || {};
}, function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
app.controller('HelloCtrl', function($scope, http) {
http.getData('https://www.reddit.com/.json').then(function(){
alert(http.data.kind);
})
});

How to pass filter params from angularjs to spring restcontroller with #MatrixVariable

I am not able to find a way to use angularjs's $http.get to pass filter params.
Url is:
http://localhost:8080/template/users/query;username=abcd;firstName=ding...
RestController is:
#RequestMapping(value={"/users/{query}"}, method=RequestMethod.GET)
public ResponseEntity<List<User>> queryUsers(#MatrixVariable(pathVar="query") Map<String, List<String>> filters) {
....
}
When I use the above Url directly in the browser it is working fine. However when I try to call the same using Angularjs's $http.get it is not working.
Angularjs code:
this.searchUser = function() {
var queryStr = '';
for (var key in userObj.search) {
if (userObj.search[key]) {
queryStr += ";" + key + "=" + userObj.search[key];
}
}
console.log('Url ', 'users/query' + queryStr);
if (queryStr === "") {
alert("No filters specified");
return false;
}
$http.get('users/query', angular.toJson(userObj.search)).then(function successCallback(response) {
if (response.data.errorCode) {
console.log(response);
alert(response.data.message);
} else {
console.log('Successfully queried for users ', response.data);
userObj.users = response.data;
}
}, function errorCallback(response) {
console.log('Error ', response);
alert(response.statusText);
});
};
When I call this method: I get the error as
errorCode: 400
message: "Failed to convert value of type [java.lang.String] to required type [long]; nested exception is java.lang.NumberFormatException: For input string: "query""
Even I tried to pass the query string as it is mentioned in the above URL, but still the same error. I am sure it is not even entering inside the RestController method.
How to solve this?
Using get,you can not pass JSON.
You should prepare object if you want to passed it a query string.
var queryStr = {};
for (var key in userObj.search) {
if (userObj.search[key]) {
queryStr[key] = userObj.search[key];
}
}
And your HTTP#GET call should be like this :
$http.get('users/query', {params: queryStr}).then(...
OR
$http({
url: 'users/query',
method: "GET",
params: queryStr
});

How to handle a resolved $promise with no data

In my application, I have a form in which the user can add multiple records. When the page is loaded, I need to make a GET request to check the DB for existing records. If there are records that exist, I populate them on the page. No problem there.
The issue I'm having is when the DB has no existing records, the server return a 204 No Content. In the controller, the success function still gets executed but there is no data only the $promise object and $resolved: true.
Here is the code:
Factory:
return $resource (
https://my.backend/api/records/:id",
{},
{
"getExistingRecords": {
method: 'GET',
isArray: false,
params: {id: '#id'},
withCredentials: true}
}
)
Controller:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
When the server returns "204 No Content" I get this from the console
Console Image
Is the only way to handle this to check for object properties of the records object?
For example:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records.recordName){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
Or am I missing something else?
It would have been better if you could get status code with response. There is not direct way for that. But you can workaround with an interceptor:
var resource = $resource(url, {}, {
get: {
method: 'GET'
interceptor: {
response: function(response) {
var result = response.resource;
result.$status = response.status;
return result;
}
}
}
});
And now you can:
if(records.$status === 200){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
I think you should return an empty list if there if no registers.

Categories

Resources