How do I add a parameter to an HTTP GET in angular? - angularjs

I want to pass an object in my http get
$http({
method: 'GET',
url: '/requestoffwork'
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
I tried this and it doesn't work.
$http({
method: 'GET',
url: '/requestoffwork',
someParam: $scope.dt
}).then(function successCallback(response) {
}, function errorCallback(response) {
});

If you're wanting to add parameters to the GET query string, you'll need to use the params option in the config object, like so:
$http({
method: 'GET',
url: '/requestoffwork',
params : {
someParam: $scope.dt
}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
Hopefully that helps!

Related

How to "pass variable from $http success to another $http request" in Angularjs?

I can't access the output variable from my 1st http get request, i need this data for another http Post request.
None.
$scope.submit = function(x) {
$http({
method: "GET",
url: url + 'getOSchild',
params: { ncard: x }
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild) // this has an output
}, function error(response, status) {
console.log(response)
console.log(status)
});
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: $scope.osChild //this is null
}),
header: {
'Content-Type': 'application/json'
},
}).then(function success(response) {
console.log(response)
}, function error(response, status) {});
}
I need the $scope.osChild to be present in my http post request.
Simply chain the two XHRs:
function getOSChild (x) {
return $http({
method: "GET",
url: url+'getOSchild',
params: {ncard: x}
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild); // this has an output
return response.data;
},function error(response) {
console.log(response)
console.log(response.status);
throw response;
});
}
$scope.submit = function(x) {
getOSChild(x).then(function(osChild) {
$http({
method: "POST",
url: url+'printOS',
data:{ CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild //chained
}
}).then(function success(response) {
console.log(response)
});
});
};
The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.
For more information, see
AngularJS $q Service API Reference - chaining promises
You're Missing the Point of Promises
first GET call is asynchronous so $scope.osChild setting null initially. so suggestion is to use Promises https://ng2.codecraft.tv/es6-typescript/promises/
$scope.getOSChild = function() {
var deferred = $q.defer();
$http.get(url + 'getOSchild')
.then(function onSuccess(response) {
$scope.osChild = response.data;
deferred.resolve(response.data);
}).catch(function onError(response) {
console.log(response.data);
console.log(response.status);
deferred.reject(response.status);
});
return deferred.promise;
};
$scope.submit = function(x) {
$scope.getOSChild().then(function (osChild) {
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild
}),
header: {
'Content-Type': 'application/json'
},
}).then(function onSuccess(response) {
console.log(response);
}, function onError(response, status) {});
});
};

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

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

Factory doesnt return http data response

Im trying to get http post data response using the code below (it is working).
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
$http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
console.log("erro!");
});
}
}
});
Inside of my controller, i have:
LoginService.existUser(loginObj).then(function (data){
console.log(data);
});
And i got the error:
Cannot read property 'then' of undefined
What is wrong?
Your return response.data; returns result of then function, not existUser! Modify your code like below:
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
return $http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
})
}
}
});
In this case, existUser method returns promise object, that has .then method

$http POST response from service to controller

How to get the response from Service in below case??
Service:
app.factory('ajaxService', function($http) {
updateTodoDetail: function(postDetail){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(function(response){
//return response;
});
}
})
Controller:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
In th above case, i POST the data through Controller and it was working fine but now i want the response to come in my Controller.
How to achive that??
$http returns a promise:
Return the promise
updateTodoDetail: function(postDetail){
return $http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
});
So you can do
ajaxService.updateTodoDetail(updated_details).success(function(result) {
$scope.result = result //or whatever else.
}
Alternatively you can pass the successfunction into updateTodoDetail:
updateTodoDetail: function(postDetail, callback){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(callback);
So your controller has
ajaxService.updateTodoDetail(updated_details, function(result) {
$scope.result = result //or whatever else.
})
I would prefer the first option so I could handle errors etc as well without passing in those functions too.
(NB: I haven't tested the code above so it might require some modification)
what I usually do is like this
app.factory('call', ['$http', function($http) {
//this is the key, as you can see I put the 'callBackFunc' as parameter
function postOrder(dataArray,callBackFunc) {
$http({
method: 'POST',
url: 'example.com',
data: dataArray
}).
success(function(data) {
//this is the key
callBackFunc(data);
}).
error(function(data, response) {
console.log(response + " " + data);
});
}
return {
postOrder:postOrder
}
}]);
then in my controller I just call this
$scope.postOrder = function() {
call.getOrder($scope.data, function(data) {
console.log(data);
}
}
do not forget to insert the dependency injection of 'call' services into your controller

Resources