角度工厂和控制器

时间:2016-06-24 16:44:27

标签: angularjs controller

我正在尝试了解如何使用带控制器的工厂。我见过一个例子:

angular.module('flapperNews')
  .factory('posts', ['$http', function($http) {
    var o = {
      posts: []
    }
    o.getPosts = function() {
      return $http.get('api/posts').success(function(data) {
        return data
      })
    };
    o.create = function(post) {
      return $http.post('api/posts', post).success(function(data) {
        o.posts.push(data);
      })
    };
    return o
  }])

当我在console.log(o.getPosts())时,它返回以下内容:

Promise {$$state: Object}
$$state
:
Object
pending
:
undefined
processScheduled
:
false
status
:
1
value
:
Object
config
:
Object
data
:
Array[6]
0
:
Object
_id
:
"576d4904f2aa867dadb7b286"
link
:
"aaa"
title
:
"nice weather in Australia"
upvotes
:
0
__proto__
:
Object
__defineGetter__
:
__defineGetter__()
__defineSetter__
:
__defineSetter__()
__lookupGetter__
:
__lookupGetter__()
__lookupSetter__
:
__lookupSetter__()
constructor
:
Object()
hasOwnProperty
:
hasOwnProperty()
isPrototypeOf
:

我想要的数据是在$$ [状态]下的Array [6],有没有人知道这是什么以及通常如何提取数据? 应该将数据传递给我的控制器,如下所示:

 $stateProvider
   .state('home', {
       url: '/home',
       templateUrl: 'views/posts.html',
       controller: 'PostCtrl',
       controllerAs: 'posts',
       resolve: {
         postPromise: ['posts', function(posts) {
           console.log(posts.getPosts())
           return posts.getPosts();
         }]
       }
   });

注意:这取自在线教程。我真的很感激,如果有人可以了解这一点,因为我是新来的工厂等。目前的代码并没有回复我的观点,你能告诉我哪里出错了吗?

已编辑/已添加:这是控制器的实现。当我在console.log(posts.posts)时,它返回一个空数组[]。有什么想法吗?

 angular.module('flapperNews')



     .controller('PostCtrl', [
      '$scope','posts',
        function($scope,posts){

          $scope.posts=posts.posts;

      $scope.incrementUpvotes=function(post){
              post.upvotes+=1
            }

             $scope.addPost = function(){
              if(!$scope.title || $scope.title === '') { return; }
              posts.create({
                title: $scope.title,
                link: $scope.link,
              });
              $scope.title = '';
              $scope.link = '';
            };


    }]);

1 个答案:

答案 0 :(得分:1)

您如何在控制器中调用工厂的方法?您正在发出一个返回承诺的$ http请求。

您可以在此处了解承诺:http://andyshora.com/promises-angularjs-explained-as-cartoon.html

简而言之,您可以将promises看作是立即执行的函数,但将来会返回数据(不是马上)。您必须等到承诺“解析”才能获取数据。这就是为什么在promise函数本身中包装任何需要来自promise的数据的代码是好的。

控制器中,您应该像这样调用工厂方法(getPosts())

posts.getPosts().then(function(response){

    $scope.news = response.data;  <---here is where you get your data for your news.  You cant not declare **$scope.data** outside this promise function because you will miss the data.   

});

不要忘记在您的控制器注入您的帖子服务/工厂:

controller(['posts',function(posts){ ... });

您还可以使用路径获取数据:

$stateProvider
    .state('home',{
        url:'/home',
        templateUrl:'views/posts.html',
        controller:'PostCtrl',
        controllerAs:'posts',
        resolve:{
            postPromise: ['posts', function(posts){

                return posts.getPosts().then(function(response){

                     return response.data

                });

            }]
       }
    })

然后在您的控制器中,您可以注入 postPromise ,如下所示:

controller(['postPromise',function(postPromise){ ... });

现在您可以将数据分配到控制器中的变量,如下所示:

$scope.news = postPromise;

希望我回答你的问题。如果我误解了,请提供更多细节或提供代码。

相关问题