AngularJS,$ resource,从.query()获取对象

时间:2016-09-02 09:37:34

标签: javascript angularjs angularjs-scope

需要从.query(),service:

获取一个对象
angular.
  module('core.users').
  factory('User', ['$resource',
    function($resource) {
      return $resource('users/users.json', {}, {
        query: {
          method: 'GET',
          isArray: true
         }
       });
      }
    ]);

成分:

'use strict';

angular.
  module('userDetail').
  component('userDetail', {
    templateUrl: 'user-detail/user-detail.template.html',
    controller: ['$routeParams', 'User', '$filter',
      function TaskDetailController ($routeParams, User, $filter) {
        var vm = this;

        vm.id = parseInt($routeParams["id"], 10);
        vm.users = User.query(function() {
          vm.user = $filter('currentUser')(vm.users, vm.id);
        });
      }
    ],

    controllerAs: 'vm'
  });

需要从数组中获取一个对象,使用$ routeParams id来获取当前用户'问题 - 在控制器范围内未定义vm.user,此处

vm.users = User.query(function() {
  vm.user = $filter('currentUser')(vm.users, vm.id); // all ok, i got the object
  });
console.log(vm.user) // undefined

它可以查看,我可以显示属性,但需要使用此独奏对象向服务器发出.put()请求,当某些用户道具发生更改时...

2 个答案:

答案 0 :(得分:0)

来自https://docs.angularjs.org/api/ngResource/service/ $ resource

  

HTTP GET" class" actions:Resource.action([parameters],[success],   [错误])

你应该写:

vm.users = User.query();
vm.users.$promise.then(function(response){
  vm.user = $filter('currentUser')(vm.users, vm.id);
  console.log(vm.user); // Should log the desired result
});
console.log(vm.user); //This will be undefined since it is called before the promise is resolved

答案 1 :(得分:0)

您需要声明vm.user 首先将watch放在上面。

JS:

vm.user = {};

$scope.$watch(function() {
    return vm.user;
}, function(newVal, oldVal) {

    console.log(newVal); //you can get new value here which is single object
})

vm.users = User.query(function() {
    vm.user = $filter('currentUser')(vm.users, vm.id); // all ok, i got the object
});
相关问题