Search code examples
angularjsangular-resourcengresource

$resource object empty after get request


I want to save JSON-Data from my Rest-API in a $scope variable for further usage. The problem is when the Code is executed, i see in Firebug that i've got the JSON Data sucessfully, but the problem is, that i cant save it in my Scope variable and i dont know why.

My app.js

var app = angular.module('shop', ['ngRoute','ngResource'])
  .factory('Customerservice', function ($resource) {
      return $resource('http://localhost:8080/Shop/:customer',{customer: "@customer"});
})
  .config(function ($routeProvider, $locationProvider) {
      $routeProvider.when('/name/:ID', {
          templateUrl : "Customer/customers.html",
          controller : 'customerController'
      });
})
  .controller('customerController', function ($scope,Customerservice) {
      $scope.customerinfo = Customerservice.get({customer: "Mark"});
      alert($scope.customerinfo);
});

Like i said, i've got the JSON-Data but the Problem is in my Controller "customerController". I just put the alert function in my Code to see whats in my $scope.customerinfo. And well the Content of customerinfo is just object: Object. I noticed something strange while debbuging with Firebug. It looks like that the alert is executed before the get request. This would explain why there is no data in my $scope variable. Can anyone help me here.


Solution

  • Use $promise property

    It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

    $scope.customerinfo = CustomerService.get({customer: "Mark"});
    
    console.log($scope.customerinfo); //Empty object
    

    However, the $resource service also attaches a $promise property that can be used to delay code execution until the data has arrived from the server:

    $scope.customerinfo = CustomerService.get({customer: "Mark"});
    console.log($scope.customerinfo); //Empty object
    
    //USE $promise
    $scope.customerinfo.$promise
      .then(function(info) {
        console.log($scope.customerinfo); //Fulfilled object
        return info;
    }).catch(function(errorResponse) {
        console.log(errorResponse.status);
        throw errorResponse;
    });
    

    The Resource instances and collections have these additional properties:

    • $promise: the promise of the original server interaction that created this instance or collection.

    On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

    On failure, the promise is rejected with the http response object, without the resource property.

    — AngularJS ngResource $resource API Reference