Need get one object from .query(), service:
需要从.query()获取一个对象,服务:
angular.
module('core.users').
factory('User', ['$resource',
function($resource) {
return $resource('users/users.json', {}, {
query: {
method: 'GET',
isArray: true
}
});
}
]);
component:
'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'
});
need to get one object from array, 'currentUser', with $routeParams id, problem - vm.user is undefined in controller scope, here
需要从数组中获取一个对象'currentUser',使用$ 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
it's ok for view, i can display properties, but need make .put() request to server with this solo object, when some of user props changed...
它可以查看,我可以显示属性,但需要使用此独奏对象向服务器发出.put()请求,当某些用户道具发生变化时......
2 个解决方案
#1
0
From https://docs.angularjs.org/api/ngResource/service/$resource
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
HTTP GET“类”操作:Resource.action([parameters],[success],[error])
You should write:
你应该写:
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
#2
0
You need to declare vm.user
first and put watch on it.
您需要先声明vm.user并将监视放在上面。
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
});
#1
0
From https://docs.angularjs.org/api/ngResource/service/$resource
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
HTTP GET“类”操作:Resource.action([parameters],[success],[error])
You should write:
你应该写:
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
#2
0
You need to declare vm.user
first and put watch on it.
您需要先声明vm.user并将监视放在上面。
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
});