Angular JS pass data to $http a global error handler - angularjs

I have a global error handler function for $http request.
var errorHandler = function (err) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, errorHandler)
}
How can I pass the variable i to errorHandler?
I know I can do this:
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function (err) {
// log the error
console.log('i', i) // access i
return {status: err.status, data: {result: -1}}
})
}
But if I want use a global errorHandler, what should I do?
==============
Update:
According to Leandro Zubrezki's answer, we can make it in this way:
var errorHandler = function (err, i) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function(error){
errorHandler(error, i)
})
}
This is a stupid question from newbie. :)

Do it like this:
function(error) {
errorHandler(error, i);
}

Related

Angularjs $http then is not working properly

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

Get value out of Json return

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

How to use callback in $http Angular JS?

I have an service with methods that does requests to server:
this.add = function (data, cb) {
$http({
method: 'POST',
url: path
}).then(function successCallback(response) {
cb(response);
}, function errorCallback(response) {
// TODO
});
};
When I call add() as:
genresService.add(function (data) {
// TODO
});
I get error:
TypeError: cb is not a function
at successCallback (custom.js:329)
on line:
cb(response);
this.add = function (data, callback,error) {
$http({
method: 'POST',
url: path,
data: data
}).then(callback).catch(error);
};
//then call like this
genresService.add(myData ,function (res) {
console.log(res);
}
,function(errorResponse){
console.log(errorResponse);
});
You need to pass two params in your add function - first is data and other is callback function. You are only passing one. You need to pass two arguments like this,
genresService.add( data, function (data) {
// TODO
});
The 'add' function expects 2 parameters : data & a callback :
genresService.add(data,function (response) {
// TODO use response.data I presume
});
Maybe you want to do:
this.add = function (dataToPost, cb) {
$http.post(path,dataToPost)
.then(function successCallback(response) {
cb(response.data);
}, function errorCallback(response) {
// TODO
});
};
genresService.add(someData,function (data) {
// TODO use data I presume
});
this.add = function (jsonobj, callback) {
$http({
method: 'POST',
url: path,
data: jsonobj
}).then(function(res) {
callback(res);
}, function(err) {
callback(err)
});
};
//missing data like up : i call it jsonobj and finction got res is a callback
genresService.add(jsonobj ,function (res) {
console.log(res);
}
try it

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

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;

Resources