工厂功能给出“错误:未定义

时间:2015-02-19 13:27:26

标签: javascript angularjs angular-promise

我无法对我的api进行http.get调用。这是设置:

user.js的

.config(['$stateProvider', '$urlRouterProvider',
   function($stateProvider, $urlRouterProvider) {

     $urlRouterProvider.otherwise('/hem');

     $stateProvider.state('anvandare', {
       url: '/anvandare',
       views: {
         'main': {
           controller: 'UserController',
           templateUrl: 'modules/user/user.tpl.html'
         }
       }
     });

}])

.controller('UserController', 
  ['$scope', '$http', 'userFactory', function($scope, $http, userFactory) {
    this.users = [{name: "Patrik"}];
    $scope.message = userFactory.test();

    userFactory.getUsers().then(function(users) {
      $scope.users = users;
    });
}])

.factory('userFactory', ['$http', function($http) {

   return {
     test: function() {
       return "hello world";
     },
     getUsers: function() {
       $http.get('/api/user');
     }
   };
 }]);

模块/用户/ user.tpl.html

<div class="container" ng-controller="UserController as UserCtrl">
  <h1>Users</h1>

  <p>{{message}}</p>
  <ul>
    <li ng-repeat="user in users">{{user.name}}</li>
  </ul>
</div>

所以现在,我已禁用缓存,我在请求中看不到304:s因此我知道所有响应都是新鲜的,我可以看到<h1>Users</h1> <p>{{message}}</p>并且消息是=&#34; hello world& #34;应该如此,但用户列表没有显示出来。当我看到页面上的Chrome工具时,它说

"Error: userFactory.getUsers(...) is undefined"

当键入&#39; localhost:5000 / api / user&#39;在我的浏览器中,我确实让所有用户都回到了json

[{"_id":"54e4c44f8d18e2a43f58935f","name":"Patrik","__v":0,"updated_at":"2015-02-18T16:56:47.105Z"},{"_id":"54e4c4588d18e2a43f589360","name":"Patrik Nygren","__v":0,"updated_at":"2015-02-18T16:56:56.603Z"},{"_id":"54e4c45f8d18e2a43f589361","name":"Patrik Ackerfors","__v":0,"updated_at":"2015-02-18T16:57:03.011Z"},{"_id":"54e4c4888d18e2a43f589362","__v":0,"updated_at":"2015-02-18T16:57:44.226Z"}]

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您必须从getUsers方法返回一些内容:

 getUsers: function() {
   return $http.get('/api/user');
 }