How to get response status code in angular 1.5.6? - javascript

I was trying a lot of aproaches, some of them:
$http({
method: 'GET',
url: '/Url'}).then(function successCallback(response) {
}, function errorCallback(response) {
});
var req = {
method: 'GET',
interceptor: {
response: function (response) {
console.log(response)
var result = response.resource;
result.$status = response.status;
return result;
}
},
url: url,
headers: {
'Authorization': token
}
}
$http(req).success(function (data, status, headers, config) {
console.log(data, status, headers, config);
}).error(function (data, status, headers, config) {
console.log(data, status, headers, config);
});
And a lot of others with no result, so I really need help !!!
I would grateful for any help

The first approach looks close to what you need.
function successCallback(response) {
console.log('status code: ', response.status);
}
Currently the callback is empty so we are accessing response object and logging status code from it.

The first way is the more direct way of doing but I'm pretty sure that the response functions should be anonymous. Putting a console.log() in both will help.
$http({
method: 'GET',
url: '/Url'
}).then(function(response) {
console.log(response.status);
}, function(response) {
console.log(response.status);
});
If that doesn't work just put the console.log(response) in both to see what it gets you.

You can use httpinterceptor if you want to track all your requests :
myModule.factory('myHttpInterceptor', function ($q) {
return {
response: function (response) {
// do something with success response
// status in response.status
return response;
},
responseError: function (response) {
// do something with error response
// status in response.status
return $q.reject(response);
}
};
});
myModule.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});

Related

Run HTTP post on successful post login

I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.

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

$http.post angularjs do not get in to success or error

My code is like this
$http.post("../services/myurl.aspx?Param=" + finaldata, '', { 'Content-type': 'text' })
.success(function (pricedata) {
alert (success)
})
.error(function () {
alert('we have failed to make a connection with the server. Please try after some time');
});
When I make this call neither success nor error happens.But the service is called. I am a little confused. can anyone point out what I am doing wrong?
You should use service to post data, here is how you could do it.
doSomething: function (data, url) {
return $http({
url: url,
method: 'POST',
data: data
});
},
and in your controller consume this service as
someService.doSomething($scope.MyData, $scope.Url)
.success(function (response) {
console.log("Success", response);
})
.error(function (data, status, headers, config) {
console.log("Error");
});
Try this simple code....
$http({
method: 'POST',
url: "../services/myurl.aspx?Param=" + finaldata,
})
.success(function (data, status, headers, config) {
var success="success"
alert (success);// or alert("success")
})
.error(function (data, status, headers, config) {
alert('we have failed to make a connection with server. Please try after some time');
});

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 update loggedInUser after onlogin in Mozilla Persona

I'm using Mozilla Persona on a project. I would like to update loggedInUser after onlogin. But loggedInUser is an attribute of an object passed to navigator.id.watch().
navigator.id.watch() was called once (in a AngularJS service).
Should I call it again, passing the full object? It doesn't seem right. Am I wrong? =P
Here is my service:
app.factory('persona', function ($rootScope, $http) {
navigator.id.watch({
loggedInUser: null,
onlogin: function onlogin(assertion) {
console.log(this);
$http.post('/signIn', { assertion: assertion })
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signIn', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signInError', data.data);
});
},
onlogout: function onlogout(param) {
$http.get('/signOut')
.then(function (data, status, headers, config) {
$rootScope.$broadcast('signOut', data.data);
}, function (data, status, headers, config) {
$rootScope.$broadcast('signOutError', data.data);
});
}
});
return {
signIn: function signIn() {
navigator.id.request();
},
signOut: function signOut() {
navigator.id.logout();
}
};
});
Can't you just make loggedInUser become global or at least "locally global" below the same scope as your navigator.id.watch method, just like the MDN example?
After that you can get the JSON response from the Persona service, which contains some data, including the e-mail. So you could pass that data on your AJAX response and fill the loggedInUser variable
https://developer.mozilla.org/en-US/docs/Persona/Quick_Setup#Step_3.3A_Watch_for_login_and_logout_actions
var currentUser = 'bob#example.com';
navigator.id.watch({
loggedInUser: currentUser,
onlogin: function(assertion) {
$.ajax({
type: 'POST',
url: '/auth/login', // This is a URL on your website.
data: {assertion: assertion},
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) {
navigator.id.logout();
alert("Login failure: " + err);
}
});
},
onlogout: function() {
$.ajax({
type: 'POST',
url: '/auth/logout', // This is a URL on your website.
success: function(res, status, xhr) { window.location.reload(); },
error: function(xhr, status, err) { alert("Logout failure: " + err); }
});
}
});
JSON response sample from MDN:
{
"status": "okay",
"email": "bob#eyedee.me",
"audience": "https://example.com:443",
"expires": 1308859352261,
"issuer": "eyedee.me"
}
At the navigator.id.watch call, set loggedInUser: localStorage.getItem('persona') || null (the null is important), then, when Persona login is successful, do localStorage.setItem('persona', theUserEmail), when it is failed, do localStorage.removeItem('persona').

Categories