Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from $resource.get() in AngularJS

JSON/XML from REST

{
  litm: "T00000245",
  lotn: "00004"
}

<jdeSerials>
  <litm>T00000245</litm>
  <lotn>00004</lotn>
</jdeSerials>

AngularJS controller

//Searching a product with serial number/LOTN
$scope.searchProduct = function () {
    var lotn = $scope.jdeSerials.lotn;
    console.log("searchProduct---->" + lotn);//log-->searchProduct---->00004


    $scope.JdeSerials = lotnService.get({id: lotn}, function() {
      console.log($scope.jdeSerials);//log-->[object Object] 
      console.log($scope.jdeSerials.litm);//log-->undefined!!!!!

    });

//var litm = $scope.jdeSerials.litm;
//$scope.jdeproduct = productService.get({id: litm});

};

AngularJS service

angular.module('lotnService', ['ngResource'])
    .factory('lotnService', ['$resource',
        function ($resource) {
            console.log('------lotmService-----');
            return $resource(
'http://localhost:8080/RMAServer/webresources/com.pako.entity.jdeserials/:id',
                    {},
                    {

                        update: { method: 'PUT', params: {id: '@lotn'} }
                    });
        }]);

Question

How can I get a value to $scope.jdeSerials.litm? Is there any better idea to solve this like creating a service which handles this two GETs? I think that reason is the GET method is asynchronous, but what is the best solution to handle situations like this?

EDIT/update

I changed the service call like this:

$scope.JdeSerials =   lotnService.get({id:lotn})
.$promise.then(function(jdeSerials) {
    $scope.jdeSerials = jdeSerials;
    console.log("1--------------->LITM:"+$scope.jdeSerials.litm);
 });

I got the LITM, BUT I got the errormessage as well:

TypeError: Cannot read property 'then' of undefined
like image 683
Sami Avatar asked Aug 12 '26 12:08

Sami


1 Answers

Try to create a get method in your resource.

angular.module('lotnService', ['ngResource'])
  .factory('lotnService', ['$resource', function ($resource) {
     return $resource(  'http://localhost:8080/RMAServer/webresources/com.pako.entity.jdeserials/:id',
                {},
                {
                    get: { method: 'GET', params: {id: '@lotn'}},
                    update: { method: 'PUT', params: {id: '@lotn'} }
                });
    }]);

Then in your controller, call method get from service:

lotnService.get({id:lotn}).$promise.then(
 function(jdeSerials) {
   $scope.jdeSerials = jdeSerials;
   console.log("1--------------->LITM:"+$scope.jdeSerials.litm);
});
like image 88
Nuno Salgado Avatar answered Aug 15 '26 02:08

Nuno Salgado