获取请求后 $resource 对象为空

$resource object empty after get request

我想将 JSON-我的 Rest-API 中的数据保存在 $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 变量中没有数据。谁能帮帮我。

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

试试这个

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

使用 $promise 属性

重要的是要意识到立即调用 $resource 对象方法 returns 一个空引用(对象或数组取决于 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;
});

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