I am using a service to return list of files. This service returns following.

Success case: List of file object in json format as given below with HTTP code as 200

[{"_id:"3453534","name":"File 1"},{"_id:"5756753","name":"File 2"}]

Failure case: This returns error response with error message as HTTP error code 500.

{errorMessage: "No files found for ptoject id 522b9358e4b0bab2f88a1f67"}

I am using following "query" method invoke this service.

//get the new value of files as per changed project id
            scope.files = ProjectFile.query({ projectid: scope.project._id }, function (response) {

                //Check if service response is success/fail
                if (response.servicestatus != undefined) {
                    //this is error case. Show error message.
                    alert("Failed to load list of files for this project: " + response.errorMessage);
                }
                else {
                    //update scope
                    scope.files = response;

                }
            });

Problem I am facing is response object which is converted by $query() method. I am getting response as an array which seems incorrect. Not sure why $query() is also expecting error response as array. In error case; I am getting response as array as below

response[0][0]="N";
response[0][1]="o";
response[0][2]="";
response[0][3]="f";
response[0][4]="i";
response[0][5]="l";
response[0][6]="e";
response[0][7]="s";
....
....

I am not sure why $query() is behaving like this. Not sure how to handle it in correct way. Please help.

1

There are 1 best solutions below

0
On

The query method of $resource expects the response as an array by default. The query isn't failing, but the response from the server isn't providing what query() is expecting.

If you know that only "no files" responses will not be arrays, then you can check to see if the response type is an array in order to know whether anything has been found or not.

This answer outlines an easy way to check:

scope.files = ProjectFile.query({ projectid: scope.project._id }, function (response) {

  //Check if service response is success/fail
  if (response.servicestatus != undefined) {
    //this is error case. Show error message.
    alert("Failed to load list of files for this project: " + response.errorMessage);
  }
  else if ( Object.prototype.toString.call(response) === '[object Array]' ) {
     scope.files = response;
  } else {
    //handle the lack of files found
  }
}