angularjs - 将数据从工厂返回到 Controller

标签 angularjs controller factory

我是 AngularJS 新手,这是我在 stackoverflow 中的第一个问题。我已经阅读了这个问题的很多可能的答案,但没有找到解决方案。我的工厂里有这个(我认为重要的部分在点之间):

;(() => {
app.factory('Users', users)
users.inject = ['$state', 'UserServices']

function users($state, UserServices) {
  users.users = [];
.....
  users.activeDeactive = (userId, activate) => {
     UserServices.activeDeactive(userId, activate).then(
        response => {
           console.log(response); //it shows "{status: 0}", which is the desired value
           return response;
        }
     )
  }

.....
  return users;
}
})()

这在我的 Controller 中:

;(() => {
app.controller('UsersCtrl', usersCtrl);

function usersCtrl($scope, $state, Users, users, vendors, profiles, clients) {
   Users.users = users;
.....
   $scope.activeDeactive = function(userId, activate) {
      var response = Users.activeDeactive(userId, activate);
      console.log(response); //it shows undefined
   }
.....
   };
})();

如何在 Controller 中获取“{status: 0}”?我在这个问题上停留了很长一段时间...我读过有关等待服务解析数据、等待 promise 等的内容...但我认为这个问题要简单得多,因为我'已经成功将服务信息发送到该工厂...现在的问题是将数据从工厂发送到 Controller ...非常感谢!

最佳答案

在 Controller 中使用以下语法。您的代码不起作用的原因是您编写了一个名为 Users.activeDeactive 的服务,您从 Controller 调用它但不等待响应。等待回复非常重要。如果服务调用成功,就会执行接下来的部分。在这里,您只需要像给定语法一样捕获响应。 如果出现错误,会转到错误部分。

    ;(() => {
    app.controller('UsersCtrl', usersCtrl);

    function usersCtrl($scope, $state, Users, users, vendors, profiles, clients) {
       Users.users = users;
    .....
       $scope.activeDeactive = function(userId, activate) {
          Users.activeDeactive(userId, activate).then(function(data){
      response = data;
console.log(response);
   },
   function(error){
       console.log(error);
   });

    .....

   };
})();

关于angularjs - 将数据从工厂返回到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47243224/

相关文章:

c# - 创建一个 C# 工厂

javascript - AngularJS 1.5.x 服务未正确绑定(bind)且未在 Controller 中更新

javascript - AngularJS $http.jsonp 缓存

javascript - 简单的Django-swampdragon + AngularJS实时应用

AngularJS: Controller 与服务

python - 扭曲的框架需要一些澄清

javascript - AngularJS ng-repeat 的性能问题

grails - 异步调用Controller-适用于州和县

ruby - rspec 索引示例有效但不显示示例

ruby-on-rails - 使用 FactoryGirl 验证 has_many 关联至少有一个模型