AngularJs passing parameters to a service - angularjs

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

Related

Fetch params from URL using app controller

How to pass the multiple parameters to a function using this code? I am able to pass only Username as single parameter but MarkDate is not passing to URL.
var app = angular.module("myModule", ['angularUtils.directives.dirPagination']);
//This Gets all the Pre Clients
app.controller("GetAttendance", function ($scope, $http) {
window.params = function () {
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for (var i in param_array) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
} ();
$http({
url: "../assets/services/MasterWebService.asmx/spGetAttendanceByUsernameDate",
method: "GET",
**params: { Username: window.params.Username , MarkDate : params.Markdate}**
}).then(function (response) {
console.log(response.data);
$scope.GetAttendanceData = response.data;
$scope.TotalOrders = response.data.length;
});
Your "MarkDate" param is not getting its value from the window.params object as you do with "Username". This should work:
$http({
url: "../assets/services/MasterWebService.asmx/spGetAttendanceByUsernameDate",
method: "GET",
**params: { Username: window.params.Username , MarkDate : window.params.Markdate}**
}).then(function (response) {
console.log(response.data);
$scope.GetAttendanceData = response.data;
$scope.TotalOrders = response.data.length;
});

Async Controller Action Method invoke by using 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 ^^

how to create a method in service for http post in angular?

i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;

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

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