0

I am trying to upload a file from the server but the file is not showing up. The call to the server is initiated from this segment of code:

'use strict';

angular.
module('phoneList').
component('phoneList', {
  templateUrl: 'phone-list/phone-list.template.html',
  controller: ['Phone',
    function PhoneListController(Phone) {
      this.phones = Phone.query();
      this.orderProp = 'age';
      console.log(this.phones);
    }
  ]
});

Which calls this service:

'use strict';

angular.
module('core.phone').
factory('Phone', ['$resource',
  function($resource) {
    return $resource('phones/:phoneId.json', {}, {
      query: {
        method: 'GET',
        params: {
          phoneId: 'phones'
        },
        isArray: true
      }
    });
  }
]);

The return codes are 200 and subsequently 304 which indicate a successful upload. But the console.log statement in the earlier code segment does not display the phones in the console.

1
  • The formatter did not work as expected Commented Dec 11, 2016 at 1:01

1 Answer 1

1

To log the result, use the $promise property of the $resource object:

angular.
module('phoneList').
component('phoneList', {
  templateUrl: 'phone-list/phone-list.template.html',
  controller: ['Phone',
    function PhoneListController(Phone) {
      this.phones = Phone.query();
      this.orderProp = 'age';
      //console.log(this.phones);
      //USE $promise property
      this.phones.$promise.then(function(phones) {
          console.log(phones);
      }).catch(function (error) {
          console.log("ERROR " + error.status);
      });
    }
  ]
});

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.

By using the .then method of the $promise property, the $q service delays the console.log until the data has returned from the server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.