简体   繁体   English

AngularJS控制器承诺然后不是函数

[英]AngularJS controller promise Then is not a function

i am having troubles making a promise in the controller. 我在控制器中无法兑现诺言。

Plunker Editor Sample Plunker编辑器样本

This is the code with the module, controller and the factory All works fine less when i callFactory, and wait for the response. 这是带有模块,控制器和工厂的代码,当我调用Factory并等待响应时,All的工作效率会降低。

I got in the console an error "Then is not a function" But i don't know what is wrong in the code 我在控制台中遇到错误“然后不是函数”,但我不知道代码中有什么问题

angular
    .module('sampleApp', [])
    .controller('SampleController', SampleController)
    .factory('myFactory', myFactory);

////////// FACTORY
    function myFactory () {

    var task = {
      getData : getData,
      counter:  0
    };

    return task;


    // Implementation details //
    // ---------------------- //

    function getData () {
      task.counter ++;
      var response = "FakeData";
      return response;
    }
  }

////////// CONTROLLER
  function SampleController (myFactory, $log) {
    $log.info("Sample controller initialized");

    var vm = this;
    vm.title = "SampleView";
    vm.callFactory = callFactory;
    vm.factoryResponse;

    callFactory();

    // Implementation details //
    // ---------------------- //

    function callFactory () {

      myFactory.getData()
      .then(function (data) {
        vm.factoryResponse = data;
        return vm.factoryResponse;

      })
      .catch(function () {
        $log.error("Ups! We cannot complete the request :(");
      });
    }
  }

Because your factory method getData return string . 因为您的工厂方法getData返回string If you want use then , then you method need return $promise . 如果要使用then ,则您的方法需要返回$promise Like this plunker : 像这个矮人

////////// FACTORY
function myFactory ($q) {

var task = {
  getData : getData,
  counter:  0
};
var defer = $q.defer();

return task;


// Implementation details //
// ---------------------- //
function getData (randomParameter) {
  task.counter ++;
  var secondString = ", sample factory value"
  var response = randomParameter + secondString;
  defer.resolve(response);
  return defer.$promise;
}}

More about angular $q 有关角度$ q的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM