I'm using Angular in Javascript to connect to the server, What I want to do is make reusable code.
The problem if that for each service that have to obtain data from server I have to know status response and if was 200 I have to know if the success was 1 or 0. So... This is my code at today (using promise):
function obtenerUltimasOperacionesComplejo() {
return $http
.get(ultimasOperacionesUrl,
{params: {idComplejo: 11}})
.then(obtenerDatosUltimasOperaciones)
.catch(generarError);
}
function obtenerDatosUltimasOperaciones(data) {
var mensaje = '';
var status = data.status;
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
}
}
function generarError(e){
var newMessage = 'XHR error! :';
if (e.data && e.data.description) {
newMessage = newMessage + '\n' + e.data.description;
}
e.data.description = newMessage;
logger.error(newMessage);
return $q.reject('Ups! Hubo un problema al conectarse al servidor. Intente nuevamente');
}
This part of code:
if(status == 401){
mensaje = 'Acceso no autorizado.';
return $q.reject(mensaje);
}
else if (status <> 200){
mensaje = 'Ups! Hubo un problema al conectarse al servidor. Intente nuevamente.';
return $q.reject(mensaje);
}
else if(status == 200){
var exito = data.data.success;
if(exito == 0){
mensaje = data.data.mensaje;
return $q.reject(mensaje);
}
...
I have to use it for each service that I have... The problem that I have is that I can't put in a function the code above, because I don't know how to set the variable with the corresponding service, I mean:
else if(exito == 1){
ultimasOperaciones = data.data.ultimasOperaciones;
return ultimasOperaciones;
}
This part of code changes for each service because "ultimasOperaciones" var is for this service in particular, for another service I have to use another variable and so on...
So... There is a way to disjoin this two part of code so I can reuse and don't have to copy and paste the most of the code?
Thanks!
please create a interceptor for checking every time the status of your response
http://thecodebarbarian.com/2015/01/24/angularjs-interceptors
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.