Angular js $http service:- header is not accessible inside catch block - javascript

I have tried different ways to access header inside catch block but was not able to achieve that .
First try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err, status, headers) {
console.log(headers);
q.reject(err);
});
return q.promise;
}
Console ::
undefined
Second try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err) {
console.log(err.headers('status-msg-header'));
q.reject(err);
});
return q.promise;
}
console ::
TypeError: err.headers is not a function
at payment.api.js:72
at processQueue (angular.js:14569)
at angular.js:14585
at Scope.parent.$get.Scope.$eval (angular.js:15848)
at Scope.parent.$get.Scope.$digest (angular.js:15659)
at Scope.parent.$get.Scope.$apply (angular.js:15953)
at angular.js:16248
at completeOutstandingRequest (angular.js:5396)
at angular.js:5668
Third try:
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err, status, headers) {
console.log(headers('status-msg-header'));
q.reject(err);
});
return q.promise;
}
console::
same as of second
Fourth try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
}, function(response) {
console.log(response.headers);
q.reject(response);
});
return q.promise;
}
console::
undefined
Fifth try:
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
}, function(response, status, headers) {
console.log(headers);
q.reject(response);
});
return q.promise;
}
console:
undefined
i did lots of variation but unable to access (not putting up entire list). Can anyone please help me to know what i'm missing.

.catch receive a response object, this object will contains the http headers.
demo
app.factory('dataService', function($http, $q){
return {
getPayment:function(){
$http({
url: 'www.google.com',
method: 'POST',
data: [{'name':'me'}]
}).then(function(response) {
$q.resolve(response.data);
})
.catch(function(response) {
console.log(response.headers('status-msg-header'));
console.log(response.status);
$q.reject(response.statusText);
});
return $q.promise;
}
}
})

Finally got the solution.
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails,
transformResponse: function(data) {
try {
data = JSON.parse(data);
} catch (e) {}
return data;
}
}).then(function(response) {
q.resolve(response);
},function(response) {
console.log(response.headers('status-msg-header'));
q.reject(response);
});
return q.promise;
}

Related

How to get multiple ajax responses in one function

I don't know if it's possible, but i'm trying to get multiple ajax responses and access it's values in another function.
I actually get the responses (twice each), but i'm not able to return the responses individual values.
JSFiddle
function firstResponse() {
const response1 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
response1.done(function(response1) {
test(response1);
})
}
function secondResponse() {
const response2 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
response2.done(function(response2) {
test(response2);
})
}
firstResponse();
secondResponse();
function test(response1, response2) {
console.log('Response 1', response1);
console.log('Response 2', response2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
There are various ways to achieve that. I personally would go with promises.
function firstResponse() {
return $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json'
});
}
function secondResponse() {
return $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json'
});
}
function test() {
Promise.all([
firstResponse(),
secondResponse()
]).then(result => {
console.log(result);
});
}
test();
In the test function you call a Promise.all which waits for all the individual promises to be resolved and outputs the result as an array in the order the of the promises passed to it at the time of calling.
let urls = ['https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke'];
let structure = {
method: 'GET',
contentType: 'application/json',
};
async function first() {
try {
const response = await $.ajax({
url: urls[0],
structure,
});
return response;
} catch(error) {
// Error
}
}
async function second() {
try {
const response = await $.ajax({
url: urls[1],
structure,
});
return response;
} catch(error) {
// Error
}
}
async function test() {
let response = await ('s')
return response
}
first()
.then(() => second());
Ajax calls are asynchronous so if you want to handle the two results in one function you have to do a counter yourself, something like this for the simplest kind:
function firstResponse() {
const response1 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
response1.done(function(response1) {
test("response1", response1);
})
}
function secondResponse() {
const response2 = $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
response2.done(function(response2) {
test("response2", response2);
})
}
var responses = [];
firstResponse();
secondResponse();
function test(index, data) {
responses[index] = data;
if (Object.keys(responses).length === 2) processResponses();
}
function processResponses() {
console.log(responses);
}
There are various more advanced way to handle it, like using async/await or something, but this should get your work done without much modification to your existing code.
UPDATE: for the async/await way which is my preferred way of doing things nowadays:
(async () => {
const response1 = await $.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
method: 'GET',
contentType: 'application/json',
});
const response2 = await $.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
method: 'GET',
contentType: 'application/json',
});
console.log(response1);
console.log(response2);
})();

$http POST not returning correct response

The issue I'm having is that $http POST is not returning the correct response.
The data I require is stored under config instead of data
The Http POST request:
for (var i = 0; i < filmService.filmData.length; i++) {
filmData.push({
title : filmService.filmData[i].title,
overview : filmService.filmData[i].info,
poster : filmService.filmData[i].poster,
genres : filmService.filmData[i].genres,
release : filmService.filmData[i].release
});
}
var data = angular.toJson(filmData[0]);
$http({
method: 'POST',
url:'/search',
data: data,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(function successCallback(response) {
console.log(response); //response received
});
The response I got in the console - highlighted in RED is the data I need:
Do this and you should get what you want:
$http({
method: 'POST',
url:'/search',
data: data,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(function successCallback(response) {
var data = response.data
console.log(data); //response received
});
Inside your .then function return the config.data.
The result will be like this
$http({
method: 'POST',
url:'/search',
data: data,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(function successCallback(response) {
var data = response.config.data
console.log(data); //response received
});

AngularJS http return value

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.
My first attempt was:
this.readParameter = function(key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
throw new Error("Error");
})
};
But of course it does not work because of Angular async features (response.data is undefined)
What is the way to do it? I just want to return the value (string), so I can use this function like
var a = readParameter("key1")
What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.
Delegator pattern works great here to assign $http task to some service and use callback method for response.
Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)
Basic example of Callback
var myVariable = '';
function myFunction (key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response);
}, function errorCallback(response) {
throw new Error("Error");
})
};
function myCallbackFunction(response) {
myVariable = response.data; // assign value to variable
// Do some work after getting response
}
myFunction('MY_KEY', myCallbackFunction);
This is basic example to set value but instead use callback pattern from above example.
var myvariable = '';
function myFunction (key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
myvariable = response.data; // set data to myvariable
// Do something else on success response
}, function errorCallback(response) {
throw new Error("Error");
})
};
myFunction('MY_KEY');
Don't try to mix async and sync programming. Instead use a callback to use like
readParameter("key1", callback)
for example:
this.readParameter = function(key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response)
}, function errorCallback(response) {
throw new Error("Error");
})
};
I resolve this by using promise:
Example :
in Service (invoicesAPIservice => invoicesapiservice.js) you use:
angular.module('app')
.service('invoicesAPIservice', function ($http) {
this.connectToAPI= function () {
return new Promise(function(resolve,reject){
var options = {
method:'GET',
url :'',
headers:{
'X-User-Agent': '....',
'Authorization': '....',
}
};
$http(options).then(function successCallback(response) {
resolve(response);
//console.log(response);
},function errorCallback(response) {
reject(response);
})
});
});
});
and in your Controller (mainCtrl=> mainCtrl.js):
angular.module('app').controller('mainCtrl', function($scope,invoicesAPIservice) {
$scope.connectToAPI=function () {
invoicesAPIservice.connectToAPI().then(function (content) {
console.log(content.statusText);
}.catch(function (err) {
//console.log(err);
alert("Server is Out");
});
}
});
And in your page : index.html:
<button ng-click="connectToAPI()"></button>
:)

Angular JS AJAX Call with Parameters

without the parameters of the method Get, the code works, but if the method asks for a parameter an error 404 is returned. How do I properly send parameters with Angular JS?
factory.test = function () {
var q = $q.defer();
$http({
method: "GET",
url: url + "/dataEntry/test",
data: {
sampletext : "sample"
}
})
.success(function (data, status, headers, config) {
q.resolve(data);
})
.error(function (data, status, headers, config) {
q.reject(data);
});
return q.promise;
};
[Route("test")]
public String Get(string sampletext)
{
return "Reply coming from data entry controller" + sampletext;
}
Since it's a GET request you shouldn't be sending data. You need to be sending a query string.
Change your data to params.
$http({
method: "GET",
url: url + "/dataEntry/test",
params: {
sampletext : "sample"
}
})
Source: http://docs.angularjs.org/api/ng/service/$http
$http({
url: "/saveInfo",
method: 'Post'
}).then(function(response) {
console.log("saved successfully");
}, function(response) {
console.log("Error message");
});

How do I get jqxhr.responseText from HttpResponseMessage?

This is my server side code
var response = new HttpResponseMessage
{
Content = new StringContent("FAIL FAIL"),
StatusCode = HttpStatusCode.InternalServerError,
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
This is my client side code using jquery
$.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
console.log(data);
},
error: function (jqxhr) {
console.log(jqxhr);
}
});
But when I check using firebug, my jqxhr.responseText is "".
How do I retrieve "FAIL FAIL"?
Try like this:
var ajaxReult = $.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
// console.log(data);
},
error: function (jqxhr) {
// console.log(jqxhr);
}
}).responseText;
console.log(ajaxReult);

Categories