【问题标题】:$resource object empty after get request获取请求后 $resource 对象为空
【发布时间】:2017-08-18 12:53:18
【问题描述】:

我想将我的 Rest-API 中的 JSON 数据保存在 $scope 变量中以供进一步使用。 问题是当代码执行时,我在 Firebug 中看到我已经成功获取了 JSON 数据,但问题是,我无法将它保存在我的 Scope 变量中,我不知道为什么。

我的 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);
});

就像我说的,我有 JSON 数据,但问题出在我的控制器“customerController”中。我只是将警报功能放在我的代码中,以查看我的 $scope.customerinfo 中的内容。好吧,customerinfo 的内容只是对象:对象。 在使用 Firebug 进行调试时,我发现了一些奇怪的东西。看起来警报是在获取请求之前执行的。这可以解释为什么我的 $scope 变量中没有数据。任何人都可以在这里帮助我。

【问题讨论】:

  • 如果您尝试警告对象,警告将仅显示 [object: objcet]。要查看警报中的值,您可以使用 JSON.stringify 函数对 json 对象进行字符串化。或者查看它,你可以使用console.log()。
  • 使用控制台日志代替警报
  • 做一件事,将调试器置于警报状态并打开 Chrome 开发者工具,当执行停止在该行时,只需将鼠标悬停在 $scope.customerinfo 上。您将看到 object 的内容。

标签: angularjs angular-resource ngresource


【解决方案1】:

使用 $promise 属性

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

$scope.customerinfo = CustomerService.get({customer: "Mark"});

console.log($scope.customerinfo); //Empty object

不过,$resource 服务还附加了一个 $promise 属性,该属性可用于延迟代码执行,直到数据从服务器到达:

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

Resource 实例和集合具有以下附加属性:

  • $promise:创建此实例或集合的原始服务器交互的promise

成功后,promise 将使用相同的资源实例或集合对象进行解析,并使用来自服务器的数据进行更新。这使得在resolve section of $routeProvider.when() 中使用它可以很容易地推迟视图渲染,直到资源加载完成。

如果失败,则使用 http response 对象拒绝承诺,而没有 resource 属性。

— AngularJS ngResource $resource API Reference

【讨论】:

  • ty 这解决了我的问题。我正是在寻找类似 $promise 的东西
  • 不客气。很抱歉其他人急于对您的问题投反对票。
【解决方案2】:

$resource 是异步 api,所以你不能从函数调用的直接返回中获取值,它包含一个变量 $promise,它将返回 promise,所以你需要调用它的 then 函数

试试这个

UserService.get({customer: "Mark"}).$promise.then(function(data) {
    $scope.customerinfo = data;
    alert($scope.customerinfo);
});

【讨论】:

  • $resource 对象方法不返回承诺。 $resource 工厂返回的对象没有.then 方法。 重要的是要意识到调用$resource 对象方法会立即返回一个空引用(对象或数组取决于isArray)。从服务器返回数据后,现有引用将填充实际数据。 请参阅AngularJS $resource API Reference
  • 是的,你是对的$resource 对象方法不返回承诺,但它包含返回承诺的$promise 变量,我已经根据这个更新了我的代码
  • 回答你的问题,georgeawg 帮我解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2018-01-06
  • 1970-01-01
相关资源
最近更新 更多