【问题标题】:AngularJS ngResource $resource query() Returns EmptyAngularJS ngResource $resource query() 返回空
【发布时间】:2016-12-11 11:23:57
【问题描述】:

我正在尝试从服务器上传文件,但文件未显示。对服务器的调用就是从这段代码开始的:

'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);
    }
  ]
});

调用此服务:

'use strict';

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

返回码是 200,随后是 304,表示上传成功。但是前面代码段中的 console.log 语句并没有在控制台中显示电话。

【问题讨论】:

  • 格式化程序没有按预期工作

标签: angularjs angular-promise angularjs-resource


【解决方案1】:

要记录结果,请使用$resource 对象的$promise 属性:

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);
      });
    }
  ]
});

重要的是要意识到调用$resource 对象方法会立即返回一个空引用(对象或数组取决于isArray)。从服务器返回数据后,现有引用将填充实际数据。

通过使用$promise 属性的.then 方法,$q 服务会延迟console.log,直到数据从服务器返回。

【讨论】:

  • 谢谢你,乔治。
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多