Am trying to hit web service with a directive controller, I hit the post method and got the response, but values I expected are become empty because all compiled before the success response.
This is my controller within the directive
controller: ['$scope', '$http', 'popupService','SessionUtils', function($scope, $http, popupService,SessionUtils) {
$scope.responseValue = "";
$scope.sendCSVFile = function(link, fileData) {
$scope.seriveResponse = $http({
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
and I called the controller from the directive link function like
var res = scope.sendCSVFile(attrs.getUrlModel, formData);
scope.gridUpdate(res);
the value res returning undefined, but I get the response after I binded the res. How to I get the promising response and execute the function after.!
You can get promise, not standard data, ajax is asynchronous call, so change code to:
$scope.sendCSVFile = function(link, fileData) {
return $http({ //return promise object
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
usage:
$scope.sendCSVFile(attrs.getUrlModel, formData).then(function(response){
//here ajax is completed and in response variable You have raturn from success callback
if (response)
scope.gridUpdate(response);
});
Related
I need to create service in AngularJS to return the response of HTTP requests. My problem is the asynchronous request, because after I've submitted the request, my function returns undefined instantly and does not return the response from the server.
app.service('TesteService', function($http) {
this.teste = function(data) {
var data = "*";
$http({
method: 'GET',
url: 'teste-s.php',
params: {data: "bem recebido"}
}).then(function successCallback(response) {
data = response.data;
alert(data);
return data;
}, function errorCallback(response) {
data = "500";
});
}
});
How do I fix this?
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
});
I am trying to pass an http response from my controller to a service, it works well except for getting the response to go into the controller here is my code below:
For my service
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload,callBack){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function successCallback(callBack){
console.log(callBack);
return deferred.resolve(callBack);
}, function errorCallback(callBack){
//deferred.reject(error);
console.log(callBack);
return deferred.reject(callBack);
});
return deferred.promise;
}
}
});
and for the Controller
app.controller('LoginCtrl', function($scope,$position,$rootScope,$state,ApiService) {
$scope.forms = {
'loginForm':''
}
var payload ={
'username':'',
'password':''
}
$scope.userLogin = function(form){
$scope.username = form.username.$modelValue;
$scope.password = form.password.$modelValue;
payload ={
"username":$scope.username,
"password":$scope.password
}
ApiService.login(payload, function(result){
console.log(result);
}
});
Now I don't understand because when I console.log() the response I'm able to see it in the service but doing the same on the controller I'm getting nothing.
No need to make it complex. Simply return promise from factory and use it in controller.
factory:
app.factory('ApiService',function($http,Config,$q) {
return {
login: function(payload) {
return $http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
});
}
}
});
in controller :
ApiService.login(payload).then(function(data){
// use response data
}, function(error) {
// handle error
});
You should use it like this:
ApiService.login(payload).then(function(result){
console.log(result);
});
Because you are returning a promise in your service.
Also you don't need that callback parameter, because the then method on the promise is your callback when it finishes and you can access the data your resolve it with.
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function (result){
return deferred.resolve(result);
}, function (result){
return deferred.reject(result);
});
return deferred.promise;
}
}
});
My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.
Below is my code:
this.search = function () {
var response = $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
return response;
}
this.search().then(function (response) {
console.log('conscole: ' + response.data.model)
})
this.search().then(function (response) {
console.log(response.data.model)
})
And below is my mvc method:`
List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
CandidateSearch.model = output;
CandidateSearch.baseCriteria = criteria;
return Ok(CandidateSearch);
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response
this.search = function () {
return $http({
method: 'GET',
url: '/api/TalentPool/Search'
});
}
//resolve the promise like this
this.search().then(function(response){
console.log(response.data.model)
})
This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});