posting $scope variable with $http - angularjs

JS
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/ajouterPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.nom, 'poste':$scope.poste}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};
Please, can anyone tell me what's wrong with that!! Why I can't use $scope.var in my data?

Remove the $scope parameter from the SendData function. You don't need to add it as it is already available in context of the controller, and by adding it you're creating a new variable named $scope inside of SendData which is undefined because you're not passing anything in when calling it.
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/addPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.poste, 'poste':$scope.name}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};
EDIT
Try making the $scope variables into a object. You also need to make your ng-model="foo.poste" and ng-model="foo.name"
$scope.foo = {
poste : "poste",
name: "name"
}
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/addPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.foo.poste, 'poste':$scope.foo.name}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};

Related

write angular js service to access multiple function

I am using below function to loadbenefittypes.
my get data function
$scope.loadCashBenefitTypes = function (){
$http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
url: appConfig.apiUrl + "/benefit-types/income?income_type=Cash Benefit",
}).then(function (response) {
$scope.func1 = response.data
}, function (response) {
});
}
i am using above function to load benefit types in multiple locations in my application. therefore i need to reuse this function as a service. how i convert above function and how i assign it to different drop down models
To re-factor the code to a service, return the $http promise:
app.service("myService", function($http, appConfig) {
this.getCashBenefitTypes = function (){
return $http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
params: { income_type: 'Cash Benefit' },
url: appConfig.apiUrl + "/benefit-types/income",
}).then(function (response) {
return response.data;
});
}
});
Then inject that service in the controllers:
app.controller("app", function($scope, myService) {
myService.getCashBenefitTypes()
.then(function(data) {
$scope.types = data;
}).catch(response) {
console.log("ERROR", response);
});
});
For more information, see
AngularJS Developer Guide - Creating Services

Angular: then execute before http call complete

When I call addCategory, it suppose to add my new category and then call _initAdminController() to go back to my main page and refresh the data there. But what is happening is getcourselist and getsubjectlist in initAdminController are somehow running first and then addCategory runs last. Do you know what can cause this? Am I using then correctly?
function _initAdminController() {
$scope.pageIndex = "adminTab";
console.log("reloading data");
$http({
method : 'GET',
url : 'http://testserver.com:8082/getSubjectListService'
}).then(function successCallback(response) {
$scope.updatedSubjects = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
$http({
method : 'GET',
url : 'http://testserver.hughes.com:8082/getCategoryListService'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.addCategory= function(){
var name = $scope.addCategoryData.name;
var desc = $scope.addCategoryData.description;
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : { 'Content-Type': 'application/json' },
data : {
name: name,
description: desc
}
}).then(_initAdminController(), function errorCallback(response) {
console.log(response.statusText);
});
}
Also when I use then for http get, that case is working correctly. The http get finishes first and then my scope variable get updated.
And lastly before I tried the following code and in that case, successCallback doesn't run at all. So does this mean then only works for GET?
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : {
'Content-Type': 'application/json'
},
data : {
name: name,
description: desc
}
}).then(
function successCallback(response) {
_initAdminController()
},
function errorCallback(response) {
console.log(response.statusText);
}
);
The code:
}).then(_initAdminController(), ...);
Should be:
}).then(_initAdminController, ...);

Use services in angular js to get and set a variable

I have a service function as show below
.service('ItemService', ['$http', function ($http) {
var items = [{'item_id': '1', 'item_name': 'abc'}];
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);
This code is working fine, I want to make the items dynamic, For example
var items = $http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
method: 'POST',
url: 'http://localhost/app/item/get/10',
}).then(function (response) {
return response.data;
});
How should I do this ?
You service will be like this
.service('ItemService', ['$http', function($http) {
return {
getItems: function(id) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'GET',
url: 'http://localhost/app/item/get/' + id,
})
},
setItems: function(items) {
return $http({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
url: 'http://localhost/app/item/' + items,
})
}
};
}]);
And you should call it inside you controller like this
ItemService.getItems().then(function(response){
//Retrieve the data
$scope.items = response.items;
}, function(error){
//Handle the errors
})
.service('ItemService', ['$http', function ($http) {
// I want to initialize this items array before I call getItems funtion, Anyway to do the same?
var items = [{'item_id': '1', 'item_name': 'abc'}];
//Below section I want exactly same I will change items array from my controller and also I will use getItem again to get this items array agian. My getItems should only return the items array
return {
getItems: function () {
return items;
},
setItems: function (value) {
items = value;
}
};
}]);

Pass parameter to webmethod $http post

I need to pass parameter to the webmethod below. I have value Param which need to be passed to webmethod.
var param='test'
$http({
method:"POST",
url:'/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: JSON,
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data)
{
$scope.Jobject = data.data.d;
});
Please advise.
You may pass params key for parameters or data key form body data which is not available in GET method
var params = {
name: 'This is parameter query'
}
var data = {
name: 'This is body data'
}
$http({
method: 'POST',
url: '/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: data,
params: params
}).then(function successCallback(response) {
$scope.Jobject = response.data.d;
}, function errorCallback(response) {
console.log(response);
});
or simply use
$http.post('/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod', data).then(function successCallback(response) {
$scope.Jobject = response.data.d;
}, function errorCallback(response) {
console.log(response);
});
You can use $http.post
$http.post('/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod', params)
For more details check official documentation
$http({
method:"POST",
url:'/sites/Demo/_layouts/15/demo/Demo.aspx/mywebmethod',
data: JSON,
headers: {
'Content-Type': 'application/json'
},
params: {name: param}
})
.then(function(data)
{
$scope.Jobject = data.data.d;
});
assuming you want to send that params string as a name

chrome shows the error TypeError: Cannot read property 'then' of undefined, even the promise was returned?

i have the following code for save operation:
here is my angular service: this already returns the promise
factory('customersaveService', function ($http, $q) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
var deffered = $q.defer();
$http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
.success(function (d) {
deffered.resolve(d);
})
.error(function (e) {
deffered.reject(e);
});
}
return factoryObject;
});
in here the promise is returned. therefore it shoudl not throw the error
"TypeError: Cannot read property 'then' of undefined"
the error comes from the controller's code:
$scope.SaveCustomer = function (data)
{
if ($scope.ButtonText == 'Save')
{
$scope.message = "";
$scope.submitted = true;
$scope.User = data;
console.log($scope.User);
customersaveService.SaveNewUserSrv($scope.User).then(function (d) { <=== error line
console.log('before success part');
if (d == 'success')
{
console.log('im in success part');
clearform();
}
},
function (e) {
});
}
}
why this throws the error when the promise was returned?
1.Create service like below :
2.No need of $q service.
factory('customersaveService', function ($http) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
}
return factoryObject;
});
factory('customersaveService', function ($http) {
var SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: { 'cust': data }
});
};
return {
SaveNewUserSrv: SaveNewUserSrv
};
});
And in the controller, sure you inject the service customersaveService

Resources