Search code examples
angularjsresponsengresource

Change in response to a string by using ngResource


I have a problem so the response is not a string but has the form {"0":"3","1":"2"}. I would instead get an answer like the number and so in this case is 32.

app.factory('Claims', ['$resource', function($resource) {
    return $resource('/portal/rest/registerClaim', null,
        {
            'create': { method: 'POST' }
        });
    }]);

app.controller('ClaimCtrl', ['$scope', 'Claims', function($scope, Claims) {

    $scope.registerClaim = function (PIN) {
        console.log(PIN);
        var obj = {
                "t":t,
                "a":"t",
                "b":"z",
                "c":"x",
                "d":"q"
        };

           Claims.create(obj).$promise.then(function(resp) {
            //$scope.resp = resp;

            $scope.resp = Object.keys(resp).map(function(val) {
                return val;
              }).join('');

            console.log(resp);

    }
}]);

And then in html file I have

     <div class="response-group">
         <p>{{resp}}</p>
    </div>

Solution

  • This might be what you're looking as far as I understand your question:

    var myArr = [];
    
    for (var key in resp) {
      if (typeof resp[key] === 'string' || typeof resp[key] === 'number') {
        myArr.push(resp[key]);
      }  
    }
    
    $scope.resp = myArr.map(function(val) {
      return val;
    }).join('');
    

    Make sure you perform this action in the .then() callback.

    This will convert the object property values into an array which you can then convert to a string by using the join() function.

    {"0":"3", "1", "2"}
    

    Will become:

    ["3", "2"]
    

    after Object.keys(obj), then calling .join('') on it it will become:

    "32"
    

    Use it like this:

        Claims.create(obj).$promise.then(function(resp) {
    
          var myArr = [];
    
          for (var key in resp) {
            if (typeof resp[key] === 'string' || typeof resp[key] === 'number') {
              myArr.push(resp[key]);
            }  
          }
    
          $scope.resp = myArr.map(function(val) {
            return val;
          }).join('');
        });