简体   繁体   中英

AngularJS - How do I capture JSON returned from a GET service method regardless of http status returned

I have an AngularJS app that I want to alert or capture the message of the following two returned JSON values, either on success or failure.

Two problems occur. On status code 500 I can not get the Message value of the returned JSON I get undefined when I try to alert msg . On success I can not parse the JSON either.

Message in Network console

GET inviteUsers 500 Internal Server Error

{"Message":"Users are not available"}

What do I need to do to make this work?

JSON on failure - returns status code 500

{"Message":"Users are not available"}

JSON on success

{"Message": "Invitations sent successfully"}

Controller Method

$scope.inviteUsers = function(){
  var msg = JSON.parse(createNewUserService.inviteUsers().query()["Message"]);
}

Service Method (Method GET)

var _inviteUsers = function(){

  return $resource(serviceBase + 'inviteUsers',
{
});
};

In fail condition you can access your message in error callback function

var msg;
var inviteUsers = createNewUserService.inviteUsers().query();
inviteUsers.$promise.then(function(data) {
    // success handler
    msg = JSON.parse(data)["Message"];
}, function(error) {
    // error handler
    msg = JSON.parse(error)["Message"];
});

The following helped achieve the desired result. The key was to use angularjs promises.

var msg;
$scope.inviteUsers = function(){
  var inviteUsers = createNewUserService.inviteUsers().query();
  inviteUsers.$promise.then(function(data){
   msg = JSON.parse(data).Message;
   notify(msg);
  },
  function(error){
    msg = "No invitations sent";
    notify(msg);
  });
}

You're getting the Message property wrong.

So update this:

var msg = JSON.parse(createNewUserService.inviteUsers().query()["Message"]);

to:

var msg = JSON.parse(createNewUserService.inviteUsers().query()).Message;

Update:

Regarding fail conditions, we should check it first if there's a response or the response is valid.

var msg = "Users are not available";
var resp = createNewUserService.inviteUsers().query();
if(resp)
  msg = JSON.parse(resp).Message;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM