我有一个工厂,我有发布和评论属性,这些属性值来自我的资源对象。但是当我尝试调用 getComment()函数时,它仍会返回[];
我的工厂 angular.module('flapperNews')。factory('postService',['$ resource',function($ resource){
var service = {};
var postId = 0;
var post = {};
var comments = [];
service.resource = function() {
return $resource('api/posts/:id.json', {id: "@id"},
{
'create': { method: 'POST' },
'index': { method: 'GET', isArray: true },
'show': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
};
service.setPost = function(postId) {
this.resource().show({id: postId}, function(post) {
post = post;
comments = post.comments;
});
};
service.getComments = function() {
return comments;
};
service.setPostId = function(newPostId) {
this.postId = newPostId;
};
return service;
}]);
在我的控制器中使用
....
function ($scope, Post, Comment, $stateParams, formlyValidationMessages, Page, Auth, loginForm, postService) {
postService.setPost($stateParams.id);
console.log(postService.getComments());
....
答案 0 :(得分:0)
您的代码是异步的,并且您尝试同步使用, 将该功能更改为
service.setPost = function(postId) {
return this.resource().show({id: postId}).$promise.then(function(post) {
post = post;
comments = post.comments;
});
};
并在控制器中 -
postService.setPost($stateParams.id).then(function(){
console.log(postService.getComments());
});
这样它应该有效!
因为我们等待评论属性被填满。
祝你好运