【问题标题】:Cant get restangular factory to work无法让休息工厂工作
【发布时间】:2015-07-09 20:57:03
【问题描述】:

我确定我在这里缺少一些简单的东西,但我无法让它工作.. 我想使用工厂,以便我可以在多个控制器中重用数据。

(function() {
'use strict';

angular
    .module('www')
    .factory('profileFactory', profileFactory);

profileFactory.$inject = ['Restangular'];

/* @ngInject */
function profileFactory(Restangular) {

    var service = {
        getUserData: Restangular.one('/user/profile/').getList(),
        getFriendList: Restangular.all('api/users/getfriendsinvitations/').getList()
    };
    return service;

    }
})();

控制器:

(function() {
    'use strict';

    angular
        .module('www')
        .controller('ProfileController', ProfileController);

    ProfileController.$inject = ['profileFactory'];

    /* @ngInject */
    function ProfileController() {

      activate();

      function activate(profileFactory, $scope) {
       profileFactory.getFriendList.then(function (homeFriends) {
         $scope.homeFriends = homeFriends;
       });
      }
    }
})();

而且我不断收到“TypeError: Cannot read property 'getFriendList' of undefined”

编辑:我也试过了,https://github.com/mgonto/restangular#decoupled-restangular-service,但没有运气!

【问题讨论】:

  • 请在标题中形成一个实际问题。它看起来像标签。另外,请扩展您为自己解决此问题所做的努力。您是否检查过第一/第三方库的文档?
  • 你能提供一个plunker文件吗?我们需要知道其他细节,例如:“您调用服务的方式”等。

标签: angularjs factory restangular angular-promise angularjs-factory


【解决方案1】:

您的工厂定义不正确。为了向服务消费者提供工厂函数,您应该在函数中定义工厂代码,同时返回该承诺将帮助您继续承诺链。

代码

function profileFactory(Restangular) {

    var service = {
        getUserData: function(){
           return Restangular.one('/user/profile/').getList();
        },
        getFriendList: function(){
           return Restangular.all('api/users/getfriendsinvitations/').getList();
       }
    };
    return service;
}

控制器

(function() {
    'use strict';

    angular
        .module('www')
        .controller('ProfileController', ProfileController);

    ProfileController.$inject = ['profileFactory', '$scope'];

    /* @ngInject */
    function ProfileController(profileFactory, $scope) { //<==added dependancy here

      activate();

      function activate() {
       profileFactory.getFriendList().then(function (homeFriends) {
         $scope.homeFriends = homeFriends;
       });
      }
    }
})();

【讨论】:

  • 我也发现了这个,stackoverflow.com/questions/22496041/…,所以它看起来应该可以工作!(?)
  • 没有区别..仍然是同样的错误,但这也增加了一个 jshint 错误...我将“profileFactory”注入到 activate() 函数中,所以这应该不是问题。
  • @Mackelito 从activate 函数中删除profileFactory, $scope'..看看编辑
  • 啊..你是对的! :) 现在我得到“无法读取未定义的属性 'then'”,这是另一个问题 :)
  • @Mackelito 查看更新答案,它只是更改为 profileFactory.getFriendList() 添加了函数括号
【解决方案2】:

您必须在控制器的函数中注入 profileFactory 服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多