G
G
goodnickoff2014-01-24 16:09:15
JavaScript
goodnickoff, 2014-01-24 16:09:15

AngularJS: Cancel overwriting $resource object values ​​after save() call;

var User = $resource( 
  'http://test/index.php'
);

var user = User.get({id:'1'}); 
// GET: http://test/index.php?id=1
// server returns: { "login":"foo", "name":"bar", "mail":"baz"	}

user.name = "qux";
user.$save();
 // POST: http://test/index.php?id=1
 // server returns: { "login":"foo", "name":"bar", "mail":"qux"}

In this case, when the save() method is called, the properties of the user object will be replaced with those that came from the server.
But if the server responds like this:
{
  "errors":{
     "login":"too short",
     "name":"is already using that name.",
     "mail":"invalid email."
  }
}

The properties of the user object will be overwritten and instead of them there will be an errors property containing these same errors.
Is there a way to change the behavior of $resource? I would like to check the status of the response, and based on this, decide whether to update the properties of the object or inform the user about an error.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Ruslan Lopatin, 2014-01-24
@goodnickoff

If you do not want to return an error status from the server, then you can intercept the response and reject it if there is an error indicator (a field errorsin your case). Everything is in the documentation (see actions.interceptor).

_
_ _, 2014-01-24
@AMar4enko

It may be past the checkout, of course, but I once abandoned $resource in favor of Restangular. An order of magnitude more flexible tool.
Take a look, you might like it.

M
maxaon, 2014-01-24
@maxaon

$resource is an extremely simple wrapper. I see two solutions:
1. In case of an error, the server must set the correct response code 400 or 500. Then you must independently process it in the method $promise.catch
2. Write your own wrapper. Or using other libraries, but most likely you will have to satisfy the first condition, since it is necessary for the normal functioning of REST.

G
goodnickoff, 2014-01-24
@goodnickoff

I would like to use status 200 for all server responses. And report the error in the body of the response. For example, like Facebook:

HTTP Status Code: 200
{"type" : "OauthException", "message":"(#803) Some of the aliases you requested do not exist: foo.bar"}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question