How to know the server response in web api - angularjs

I am developing Web API in MVC with AngularJS for the first time and and I want to know how to show the response message in client side, to show to the user what is happening.
Here is my code:
public HttpResponseMessage Delete(int id)
{
Product prouct = new Product { Id = id };
HttpResponseMessage response = new HttpResponseMessage();
if (prouct != null)
{
db.Products.Attach(prouct);
db.Products.Remove(prouct);
if (db.SaveChanges() > 0)
{
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateResponse(HttpStatusCode.NotFound);
}
}
return response;
}
$scope.DeleteProduct = function (ID) {
if (confirm("Are you sure to delete this product?")) {
$http({
url: 'http://localhost:52795/api/Test',
method: 'DELETE',
params: { Id: ID }
}).success(function (data, xhr, status) {
$scope.GetAllProducts();
console.log(data);
alert(status);
}).error(function (xhr, status) {
console.log(xhr, status);
alert( status);
})
}
}

Have you tried using $http().then() ?
$http({
url: 'http://localhost:52795/api/Test',
method: 'DELETE',
params: { Id: ID }
}).then(function successCallback(response) {
alert(response.data); // This represents the response
}, function errorCallback(response) {
// If some error has occured
});
For more about http requests read this
https://docs.angularjs.org/api/ng/service/$http

Related

not getting $rootScope.updatedata from controller to html view

I am trying to get $rootScope.updatedata from the controller to the view using $rootScope of angularjs. When I pass the data gotten from the server response to the view, the data is null. From the controller, the data has a value. Here is the snippets
app.controller("updateCtrl",["$scope","$rootScope","$location","$cookies","$http",
function($scope,$rootScope,$location,$cookies,$http){
getUserDetails: function (email) {
$http({
method: 'GET',
url: '/updateprofile',
params: {email: email}
}).then(function successCallback(response) {
if (response.status == 204) {
} else if (response.status == 200) {
alert("email24 "+response.data); //this returns an object
$rootScope.updatedata = response.data; //passing to the view }
}, function errorCallback(response) {
alert(JSON.stringify(response));
});
}
}
here is how I am getting it in the view
<input formcontrolname="firstName" value="{{updatedata.email}}" />
spring controller snippets
#RequestMapping(value = {"/updateprofile"}, method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseData<Client> updateByEmail( #RequestParam("email") String email) {
this is my challenge
Using $rootscope in this situation will not help you. In general, try avoiding using it, it's a bad practice. Try something like this instead:
app.controller("updateCtrl",["$scope","$location","$cookies","$http",
function($scope,$location,$cookies,$http){
$scope.updatedata = {
email: "",
//rest of your fields
};
getUserDetails: function (email) {
$http({
method: 'GET',
url: '/updateprofile',
params: {email: email}
}).then(function successCallback(response) {
if (response.status == 204) {
} else if (response.status == 200) {
alert("email24 "+response.data); //this returns an object
$scope.updatedata.email = response.data.email;
//populate rest of the fields
}
}, function errorCallback(response) {
alert(JSON.stringify(response));
});
}
}

Angularjs $http then is not working properly

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
});

Calling method using $http Post in AngularJS

I am trying to call the method ProcessCriteria in AngularJS below but for some reason I am keep getting error message:
VM18010:1 POST http://example.com/api/TalentPool/ProcessCriteria 404
(Not Found)
Below is my Calling code:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: param
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
And my Server side method:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(string Item, string SolrLabel)
{
var itm = Item;
var solr = SolrLabel;
return Ok();
}
Any suggestions please?
ASP.net cannot match your request in its Route Table because you have 2 parameters in your action and the router doesn't understand it.
it expects a data object that your parameters warp to this.
First of all, make a Model like it:
public class Criteria
{
public string Item { get; set; }
public string SolrLabel { get; set; }
}
then change your action:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(Criteria criteria)
{
var itm = criteria.Item;
var solr = criteria.SolrLabel;
return Ok();
}
Update
and update your javaScript part with JSON.stringify:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(param)
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
You can create a class as said by in above answer and you can pass data in http post like this
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' || typeof data != null) {
obj.data = data;
}
$http(obj).then(function(response){
},function(error){
});
I got i working, below is the code for others if they get stuck on it.
var pvarrData = new Array();
pvarrData[0] = JSON.stringify(item.Key);
pvarrData[1] = JSON.stringify(SolrLabel);
pvarrData[2] = JSON.stringify($localStorage.message);
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) {
// failed
console.log('facet post error occured!');
});

error in web api controller when getting value send from js

i am new in angularjs i have a project where some get and post method
this is my js
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope, $http) {
$scope.joblist = function (Data) {
$scope.job = [];
$.ajax({
url: "/JobApi/getjoblist",
dataType: 'jsonp',
method: 'GET',
data: Data,
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.$apply(function () {
debugger;
if (response != null) {
$scope.divstateList = false;
$scope.divjobList = true;
$scope.job = response;
}
});
})
.error(function (error) {
alert(error);
});
}
});
And this is my web api controller
[System.Web.Http.Route("JobApi/getjoblist")]
[System.Web.Mvc.HttpPost]
public List<Getjoblist> getjoblist([FromBody]string Data)
{
try
{
JobBL objbl = new JobBL();
var joblist = objbl.Citywisejoblist(Convert.ToInt32(Data));
List<Getjoblist> list = new List<Getjoblist>();
foreach (var t in joblist)
{
Getjoblist GetAll = new Getjoblist();
GetAll.jobID = Convert.ToInt32(t.ID);
GetAll.jobtital = t.Title;
GetAll.jobdescription = t.Description;
GetAll.jobimage = t.JobImage;
list.Add(GetAll);
}
return list;
}
catch (Exception ex)
{
throw ex;
}
}
not getting the value in controller send from js how to solve the problem please help me

Spring Controller is not accepting the file sent by the angular controller

I'm posting some form data to the Spring controller and if it is successful, again I'm posting two files from Angular controller to Spring controller:
$http.post('userdetails', formData).success(function(response) {
if ($scope.items.length > 0) {
for (var i = 0; i < $scope.items.length; i++) {
$scope.uploadItem(response.id, $scope.items[i]);
}
}
});
This is my uploadItem function:
$scope.uploadItem = function(id, file) {
var data = new FormData();
data.append('id', id);
data.append('file', file);
$http.post('multipleSave', data, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: {
'Content-Type': undefined
}
}).success(function(data) {
$log.debug("Upload Successfull");
$log.debug("File upload: Success calling ");
alert(data);
alert("hi");
}).error(function(error) {
$log.debug("Upload failure");
alert(error);
});
};
This is my Spring Controller code
#RequestMapping(value="/multipleSave", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
System.out.println(fileName);
}
Content in the MultipartHttpServletRequest request is empty.
You should have encryption type set to multipart/form-data in your request headers.
$http.post('multipleSave', data, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: {
'Content-Type': undefined,
enctype:'multipart/form-data'
}
})

Resources