【问题标题】:How to use promises between angular factories and controllers?如何在角度工厂和控制器之间使用承诺?
【发布时间】:2016-09-30 23:28:44
【问题描述】:

工厂:

function thingyFactoryFunction($http) {
    return {
      search: function(city, state) {
        $http({
          method: 'POST',
          url: 'http://localhost:7500/search',
          data: {city: city, state: state}
        }).then(function successCallback(res) {
          return res
        })
      }
    }
  }

这是我的控制器。我希望控制器简单地从上面的工厂获取响应,因此我可以将 vm.thing 设置为等于承诺响应。但是,我不断收到错误消息,如果我再看到一次,我会发疯:'TypeError: Cannot read property 'then' of undefined'。

function thingyIndexControllerFunction(thingyFactory) {
    var vm = this;
    vm.city;
    vm.state;
    vm.search = function() {
      thingyFactory.search(vm.city, vm.state).then(function(res) {
        console.log(res);
      })
    }
  }

【问题讨论】:

  • 只需在$http之前添加return
  • 首先,你不应该从你的控制器调用搜索工厂函数为thingyFactory.search而不是thingy.search?

标签: angularjs promise factory angular-controller


【解决方案1】:

您的工厂/服务搜索方法未返回任何内容。您试图访问 .then() 什么都没有(未定义)。 $http 本身返回一个承诺对象。 尝试关注。

app.factory('thingyFactory', function($http) {
  return {
    search: function(city, state) {
      //This will return promise object.
      return $http({
        method: 'POST',
        url: 'http://localhost:7500/search',
        data: {
          city: city,
          state: state
        }
      });
    }
  }
});

在控制器中,

app.controller('thingyIndexController', function($scope, thingyFactory) {
  var vm = this;
  vm.search = function() {
    var promise = thingyFactory.search(vm.city, vm.state);
    //after promise resolved then() method get called
    promise.then(function(res) {
      console.log(res);
    })
  }
});

【讨论】:

  • 您说“您的工厂/服务没有返回任何东西。”... 为什么它没有返回任何东西?它是否没有返回整个 Search 方法,在 { } 块中的“return”一词之后指示?
  • 对不起,我的意思是 thingyFactory.search 方法。我的错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多