in my code I have a Factory with ng.resource:
.factory('company', function($resource){
return $resource(appHelper.apiPath('auth/company/info'), {}, {
update: {
method: "PUT"
}
});
});
If I submit the form in my Controller everything works fine as far as the api gives a positive response.
In case of an error the api returns a json object with http 200. In my callback function I validate the response:
$scope.saveCompanyForm = function (company) {
company.$update(
function(data) {
if(data.status == 'ERROR') {
alert("error from api")
} else {
alert("no error")
}
}, function(error) {
alert("error")
}
The problem is if the api returns an error the form cleared.
If the API response with http 500 or http 404 the form is not cleared.
Is there any possibility to prevent angular to reset the form?
Thanks
best
You can always save it before and apply after the callback.
$scope.saveCompanyForm = function (company) {
var saved_company = company;
company.$update(
function(data) {
if(data.status == 'ERROR') {
alert("error from api")
company = saved_company;
} else {
alert("no error")
company = saved_company;
}
}, function(error) {
alert("error")
company = saved_company;
}
Related
If i have one API server then the API is send ajax data with JSON format :
{"status":304,"message":"Cannot delete data where PK is empty or > 1"}
how to AngularJS $http post call the status and message to alert bootbox?
here my AngularJS $http post
$http({
method: "POST",
url: apiUrl('disable_assethw'),
data: {
id: id
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function successCallback(response) {
if(response.status == 304) {
bootbox.alert("Something went error.." + response.data.message);
} else {
$scope.getAssetHW();
}
}, function errorCallback(response) {
bootbox.alert("Something went error.." + response.status);
});
thanks for advise.
When doing a POST request with JavaScript objects as data, use the AngularJS default content type (which is automatically set to application/json). The $http service also automatically encodes JavaScript objects as JSON strings.
Only response with status in the range 200-299 are processed by the success handler. Status outside the range are processed by the rejection handler:
$http({
method: "POST",
url: apiUrl('disable_assethw'),
data: {
id: id
},
headers: {
̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶x̶-̶w̶w̶w̶-̶f̶o̶r̶m̶-̶u̶r̶l̶e̶n̶c̶o̶d̶e̶d̶'̶
}
}).then(function successCallback(response) {
̶i̶f̶(̶r̶e̶s̶p̶o̶n̶s̶e̶.̶s̶t̶a̶t̶u̶s̶ ̶=̶=̶ ̶3̶0̶4̶)̶ ̶{̶
̶b̶o̶o̶t̶b̶o̶x̶.̶a̶l̶e̶r̶t̶(̶"̶S̶o̶m̶e̶t̶h̶i̶n̶g̶ ̶w̶e̶n̶t̶ ̶e̶r̶r̶o̶r̶.̶.̶"̶ ̶+̶ ̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶.̶m̶e̶s̶s̶a̶g̶e̶)̶;̶
̶}̶ ̶e̶l̶s̶e̶ ̶{̶
$scope.getAssetHW();
̶}̶
}, function errorCallback(response) {
//HANDLE 304 status HERE
if(response.status == 304) {
bootbox.alert("Something went error.." + response.data.message);
} else {
bootbox.alert("Something went error.." + response.status);
};
});
From the Docs:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted.
— AngularJS $http Service API Reference
Note: A status of -1 usually indicates the browser rejected the request with a CORS problem that violates same-origin policy.
you said it is json response and you used: application/x-www-form-urlencoded , which is wrong.
The best practice to handle rest/api call is:
Create 1 common/general function which is accessible in whole application which will manage your post api call(add api response to callback):
postAPICall(url, body, data) {
let headers = new Headers({'Content-Type': 'application/json'});
this.http
.post(url,
body, {
headers: headers
})
.map(
response => response.json())
.subscribe(
response => {
data(response);
},
err => data(this.handleError(err)); //handle error here
);
}
call this function wherever required(in component or service):
var yourJSONBody = {
"param-1": "",
"param-2": "",
//....
}
}
this.myCommonService.postAPICall("localhost:8080/app/", yourJSONBody, data => {
if (data.status == "304") {
//do stuff
//this.msgs.push({severity: 'error', detail: data.message});
}
else {
//do stuff
}
});
error handler function:
private handleError(error: any) {
let description = 'There was an error: ' + error.status;
let errors = {
errorcode: error.status,
errorstatus: error.statusText,
errordescription: description
};
return errors;
}
We are trying to integrate the Wizcorp PhoneGap facebook plugin (https://github.com/Wizcorp/phonegap-facebook-plugin) to support the login process in a new Ionic app.
The login with Facebook seems to work just fine for a new user. The problem is when the users sign off and try to log back in he get the error:
Facebook error: Session was closed and not closed normally
what are we doing wrong here ?
Here's the code that we are using right now:
function fbLogin() {
facebookConnectPlugin.login(['email'], function (response) {
alert("Login Successfull");
alert(JSON.stringify(response));
}, function (error) {
alert("Login ERROR");
alert(JSON.stringify(error));
})
}
function getDetails() {
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status === 'connected') {
alert("You're connected!");
var userID = response.authResponse.userID;
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,picture.width(400).height(400)', [], function (result) {
alert(JSON.stringify(result));
})
} else if (response.status === 'not_authorized') {
alert("Not Autherized!");
} else {
alert("You're not loggin into Facebook!");
}
});
}
function fbLogout() {
facebookConnectPlugin.logout(function (response) {
alert("Logout success");
alert(JSON.stringify(response));
}, function (error) {
alert("Logout ERROR");
alert(JSON.stringify(error));
})
}
We have checked this link:
https://github.com/Wizcorp/phonegap-facebook-plugin/blob/master/TROUBLESHOOTING.md#no-reply-from-login
however when we try to implement the code below - we get an error
Tyeperror cordova.getActivity is not a function
PackageInfo info = cordova.getActivity().getPackageManager().getPackageInfo("com.goapes.golearn", PackageManager.GET_SIGNATURES);
The above link tells us that we need another Hash Key in our Facebook App Dashboard, so is there another way of obtaining this Hash?
I think you better to try this plugin. Because I developed a app using this plugin and it's in production now. :)
here check this
I use Parse.com cloud to manage my database for mobile application. When I save in table user some user with the same username or email it gives me the error:
POST https://api.parse.com/1/users 400 (Bad Request)
I understood by myself that error appears when the username or email are the same in different users. Is there a method to return the reason of the error like "this mail is already chosen"? Below my code:
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
alert("Save error");
console.log(error);
}
});
},
Looks like you aren't using response.error(error) anywhere...
Try
saveUser: function() {
this.utente.save(null, {
success: function(persona) {
//console.log("modello salvato nel db");
var id = persona.get("objectId");
window.localStorage.setItem('parseId', id);
},
error: function(error) {
response.error(error);
}
});
}
And then in your native script console.log the error.code and error.message.
Finally diving into meteor. I have a small problem regarding http get requests.
On the client a simple call is executed to get data from the server.
if (Meteor.isClient) {
Template.liveprice.helpers({
price: function() {
Meteor.call('getPrice', function(error, response) {
if (error) {
return error;
} else {
return response;
}
})
}
})
}
On the server data is retrieved from a live and public API. It works fine on the server, but an undefined result is send back to the client. What am I missing here?
if (Meteor.isServer) {
Meteor.methods({
getPrice: function() {
var url = 'https://www.bitstamp.net/api/ticker/';
var req = HTTP.call('GET',url,function(error, result) {
//console.log(result);
if (result.statusCode == 200) {
var last = result.data.last;
console.log(last);//this shows the desired result in the server's console
return last;//sends back undefined to the client
} else {
return error;
}
});
}
})
}
#epascarello is right. Luckily, Meteor's HTTP works synchronously as well thanks to fibers. Try this:
Meteor.methods({
getPrice: function() {
var url = 'https://www.bitstamp.net/api/ticker/';
var result;
try {
result = HTTP.get(url);
check(result.data.last, String);
return result.data.last;
} catch (error) {
throw new Meteor.Error('get-price-failed', 'Could not retrieve the price.');
}
}
});
I have an API built in Laravel which returns JSON in a format such as this:
{
"data":{
"errors":{
"username":"The username has already been taken.",
"email":"The email has already been taken."
}
},
"success":true,
"status":400
}
In this case, I'm trying to create a user with a username and email address which already exists. This is the Angular $resource code I'm using inside my controller for that:
var user = new User({
username: $scope.user.username,
email: $scope.user.email,
password: $scope.user.password
});
var response = user.$save(function(data) {
console.log(data);
}, function(data) {
if (data.status === 400) {
angular.forEach(data.data.data.errors, function(error) {
console.log(error);
});
}
});
So what this is doing is sending a POST request to /users on the API and if it comes back with a non-200 status code, it's checking if it's a 400 code which means a validation error and console.log'ing those error messages. Sure enough, I get the error messages output to the console.
What I'm wondering is, if there's a better way to access the error messages than data.data.data.errors. Seen as the API wraps the response data in a data field, and Angular returns the $resource of the request rather than the actual server response, it leads to a rather unsightly amount of properties being used to get the error messages.
Is there a better way to do this?
I think the short answer is 'no'. However, if it were me I would probably shuffle some of the variables to make things a bit nicer.
user.$save(function(data) {
console.log(data);
}, function(response) {
if (response.status === 400) {
var data = response.data.data
angular.forEach(data.errors, function(error) {
console.log(error);
});
}
});
If I had control over the api i would not be wrapping the errors in the redundant tertiary data object. This gives an entirely acceptable bit of code imo.
{
"errors":{
"username":"The username has already been taken.",
"email":"The email has already been taken."
},
"success":true,
"status":400
}
user.$save(function(data) {
console.log(data);
}, function(response) {
var data = response.data
if (data.status === 400) {
angular.forEach(data.errors, function(error) {
console.log(error);
});
}
});