Async Controller Action Method invoke by using AngularJS - angularjs

I am new to AngularJS, I want to know how to call an Async Controller Action Method in MVC by angularJS. I already tried with below code. Can someone help me in this. Here is my AngularJS code
$scope.updateEmp = function () {
var response = $http({
method: "post",
url: "/Home/UpdateCustomer",
data: JSON.stringify($scope.Customer),
dataType: "json"
}).success(function () {
$scope.cancel();
toaster.pop('success', "Success", 'Updates Successfully...!!');
// showAlert("alert-success", "Updated!");
}).error(function () {
toaster.pop('error', "Error", 'Error while getting data', null, 'trustedHtml');
// alert("Error while getting data");
});
// return response;
}
My Action Method is below
[HttpPost]
public async void UpdateCustomer(Customer Upcustomer )
{
await System.Threading.Tasks.Task.Run(() =>
{
using (BusinessEntities dbContext = new BusinessEntities())
{
var customer = dbContext.Customers1.First(c => c.CustomerID == Upcustomer.CustomerID);
customer.Fname = Upcustomer.Fname;
customer.Lname = Upcustomer.Lname;
customer.Age = Upcustomer.Age;
customer.Adderss = Upcustomer.Adderss;
customer.ContactNo = Upcustomer.ContactNo;
dbContext.SaveChanges();
// return EmptyResult;
// return Json(customers, JsonRequestBehavior.AllowGet);
//return View(customers);
}
});
}

I dont know where your controller method is declared but i suggest it should look like this:
$scope.getAllCustomers = function(){...}
and then in the callback function:
}).success(function () {
$scope.getAllCustomers();
If this is not what you meant, please specify the problem more clearly ^^

Related

AngularJs passing parameters to a service

I want to input Id via post method and get data for that Id back from database. I'm currently getting an error "employeeID is not defined" in my controller code.
Controller code:
$scope.employeeID = '10';
function test() {
var getData = myService.getEmployee(employeeID);
getData.then(function (emp) {
$scope.employees2 = emp.data;
}, function () {
alert('Error in getting records');
});
}
test(employeeID);
Service code:
this.getEmployee = function (employeeID) {
var response = $http({
method: "post",
url: "Home/getEmployeeByNo",
params: {
id: JSON.stringify(employeeID)
}
});
return response;
}
HomeController code:
public JsonResult getEmployeeByNo(string EmpNo)
{
using (InsiteEntities dataContext = new InsiteEntities())
{
int no = Convert.ToInt32(EmpNo);
var employeeList = dataContext.Employee.Find(no);
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
Change
From
var getData = myService.getEmployee(employeeID);
To
var getData = myService.getEmployee($scope.employeeID);
You should pass EmpNo parameter inspite of id parameter in params object, so that the URL will form like Home/getEmployeeByNo?EmpNo=123
this.getEmployee = function (employeeID) {
var response = $http({
method: "post",
url: "Home/getEmployeeByNo",
params: {
EmpNo: employeeID //changed to `EmpNo`
}
});
return response;
}
Also pass employeeID from $scope as describe in Sajeeth's answer like myService.getEmployee($scope.employeeID);

AngularJS Controller function - TypeError: object is not a function

I am creating an email application that makes RESTful calls to Google APIs. I am using AngularJS and Java. I have had some success so far but I am unable to delete an email because I keep getting this error: TypeError: object is not a function.
My Angular knowledge is limited.
In my html I call the function deleteEmail and pass an email id.
Here is the controller:
app.controller('InboxController', function($rootScope, $scope, $cookies,
$location, InboxService) {
$rootScope.loggedIn = true;
$scope.emails = InboxService.getMessages().success(function(jsonData) {
$scope.emails = jsonData;
});
$scope.deleteEmail = function(id) {
$scope.id = {
'id' : id
};
// Parse to JSON
var responseJSON = angular.toJson($scope.id);
// Make call to InboxService
var response = InboxService().del(responseJSON).success(
function(jsonData) {
response = jsonData;
if (response == 'success') {
alert('Message deleted');
} else {
alert('Message not deleted');
}
});
}
});
The method $scope.emails works fine. It is the $scope.deleteEmail that is giving the error.
Here is the service:
app.factory('InboxService', function InboxService($http) {
var exports = {};
// Get a list of all emails
exports.getMessages = function() {
return $http.get('resources/inbox/get').error(function(data) {
console.log('There was an error!', data);
});
};
// Delete an email
exports.del = function(id) {
console.log('id ' + id);
return $http({
method : 'POST',
url : 'resources/inbox/delete',
data : id,
headers : {
'Content-Type' : 'application/json'
}
});
};
return exports;
});
I don't think I am getting as far as the service though. The problem seems to be with the controller.
Console output:
TypeError: object is not a function
at Scope.$scope.deleteEmail (http://localhost:8080/NewProject/js/controllers.js:64:18)
at Parser.functionCall (http://localhost:8080/NewProject/bower_components/angular/angular.js:10903:21)
at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:8080/NewProject/bower_components/angular/angular.js:19259:17)
at Scope.$get.Scope.$eval (http://localhost:8080/NewProject/bower_components/angular/angular.js:12811:28)
at Scope.$get.Scope.$apply (http://localhost:8080/NewProject/bower_components/angular/angular.js:12909:23)
at HTMLButtonElement.<anonymous> (http://localhost:8080/NewProject/bower_components/angular/angular.js:19264:23)
at http://localhost:8080/NewProject/bower_components/angular/angular.js:2853:10
Pls be sure you called deleteEmail(id) from within html with right syntax without $scope
I got it working. I changed the Controller delete method to this:
$scope.delete = function (id) {
InboxService.delete(id).success(function() {
$scope.loadInbox();
});
};
And the Service method to this:
// Delete an email
exports.delete = function(id) {
console.log('id ' + id);
return $http({
method : 'DELETE',
url : 'resources/inbox/delete',
data: id,
headers : {
'Content-Type' : 'application/json'
}
});
}

Angular JS. Refresh a list after promise completes

I have a model that I am using to hold my data in angular:
var FuelProcessingModel = function (carrierService) {
this.myArray = [];
};
That model has an array of MyObjects that I get from the DB:
var MyObject = function () {
//stuff
}
I update this using a REST call:
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
service.add(myObject);
};
Which I use a service to hit the Server:
this.add = function (myObject) {
$http({
method: "POST",
url: "theServer",
data: myObject
});
}
The REST service just adds to the database, It doesn't return anything.
I need to reload the data from the database after the update is finished, so that my records now have all newly associated ID's and pertinent data.
I cannot just do:
window.location.reload();
The user starts by selecting a value from a drop down list to decide which list of data they start off seeing. I cannot / do not want to pass the value to it, mainly because it is in its own partial view, with its own controller, because it is used on many pages.
I tried doing:
$scope.add = function () {
//same as above
//this
service.get().then(function(result) { $scope.model.myArray = result.data; });
};
Obviously the problem here is the promise isn't complete before the DOM reloads the page. So the user saw themself add an item to the array and it vanished.
Do I want to load the page after the promise is complete? (How would I do that?)
should I return the updated data from the REST service and reset the current value? (seems like the same promise issue)
Is there a better practice that I do not know about?
UPDATE
For Bergi:
this.get = function (key) {
return $http({
method: "GET",
url: "theServer" + key
})
.success(function (data) {
return data;
});
}
I think you want to chain your two promises:
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
return service.add(myObject).then(function() {
return service.get();
}).then(function(result) {
$scope.model.myArray = result.data;
});
};
and
this.add = function(myObject) {
return $http({
// ^^^^^^ return a promise here
method: "POST",
url: "theServer",
data: myObject
});
};
You can wrap your service call in a deferred promise, and on return success re-init your data from the controller..
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
service.add(myObject).then(function (response) {
// here's where you'd do whatever you want to refresh your model
}),
function (err) {console.log(err);};
};
And the service:
this.add = function (myObject) {
var deferred = $q.defer();
$http({
method: "POST",
url: "theServer",
data: myObject,
success: function (response) {
deferred.resolve(err);
},
error: function (err) {
deferred.reject(err);
}
});
return deferred.promise;
}

Why does my angular/express GET work but not POST?

Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}
Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);

AngularJS $Resource - Callback always triggers the error function even though server returns a HTTP 200 response

I consume a REST service using $resource. Why is it that the error callback function is always triggered even though I get a Http: 200 (Ok) response from the server? I've tried 2 ways of setting up the callback functions and both have the same issue.
Here is the Angular controller where I consume the service:
appRoot
.controller(
'BatchTaskController',
['$scope', 'batchTaskService', function ($scope, batchTaskService){
$scope.runImportIntermediariesTask = function () {
batchTaskService.runImportIntermediariesTask().$promise.then(
function (value) { alert('success') },
function (error) { alert('error') }
);
};
$scope.runImportVantageTransactionsTask = function () {
batchTaskService.runImportVantageTransactionsTask(
function () { alert('success'); },
function () { alert('error'); }
);
};
$scope.runProcessVantageTransactionsTask = function () { batchTaskService.runProcessVantageTransactionsTask(); };
}]);
Here is the Angular service:
var angularVectorServices = angular.module('angularVector.services', ['ngResource']);
angularVectorServices.factory('batchTaskService', ['$resource' , function ($resource) {
return $resource(
"http://localhost:58655/api/BatchTask/:action",
{
action: "#action"
},
{
runImportIntermediariesTask: {
method: "POST",
params: {
action: "RunImportIntermediariesTask"
}
},
runImportVantageTransactionsTask: {
method: "POST",
params: {
action: "RunImportVantageTransactionsTask"
}
},
runProcessVantageTransactionsTask: {
method: "POST",
params: {
action: "RunProcessVantageTransactionsTask"
}
}
}
);
}]);
I am using WebApi. Here is the Server ApiController Code:
public HttpResponseMessage RunImportIntermediariesTask()
{
// _importIntermediariesTask.Run();
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
public HttpResponseMessage RunImportVantageTransactionsTask()
{
//_importVantageTransactionsTask.Run();
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
Take this as sample, try to make your action as this one below, setting up your code response code on HttpStatusCode.Whatever:
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}
Hope this helps.

Resources