使用AngularJS中的promise管理来自控制器的服务回调

Managing service callbacks from controller using promises in AngularJS?

本文关键字:控制器 服务 回调 AngularJS 中的 promise 管理 使用      更新时间:2023-09-26

当从控制器调用服务函数时,我必须管理回调。我的想法是将服务功能封装在promise中,但我不能直接从控制器引用服务功能。相反,我必须创建另一个函数来处理视图事件。

function exampleSrv($q) {
  this.exampleFn = function() {
    var q = $q.defer();
    // Do something
    q.resolve();
    return q.promise; 
  };
}
function exampleCtrl(exampleSrv) {
  this.exampleFn = exampleSrv.exampleFn;

/* This works but I want to avoid this if possible
  this.clickHandler = function() { 
    this.exampleFn()
        .then(function() {
          console.log('yay');
        })
  };
*/
/* And instead do something like this but as a reference not as a call
  this.exampleFn()
      .then(function() { 
        console.log('yay');
      })
*/
}

有更好的方法吗?

示例:http://plnkr.co/edit/jg5yoC?p=info

简而言之,没有,没有更好的方法。事实上,这是解决这些问题的明智方式。

实际上,你可以尝试这样的方法:(我遇到了plunker问题,否则会创建一个)

// Example Service
function exampleSrv($q) {
  this.exampleFn = function() {
    var q = $q.defer();
    // Do something
    q.resolve();
    return q.promise.then(function() {
      return {
        "data": "12345"
      };
    });
  };
}
// Example Controller
function exampleCtrl(exampleSrv) {
  var ctrl = this;
  exampleSrv.exampleFn().then(function(data){
     ctrl.exampleFn = data;
  });
  /* This works but I want to avoid this
  this.clickHandler = function() { 
    this.exampleFn()
        .then(function() {
          console.log('yay');
        })
  };
*/
  /* And instead do something like this 
  this.exampleFn()
      .then(function() { 
        console.log('yay');
      })
*/
}
angular.module('example', [])
  .service('exampleSrv', exampleSrv)
  .controller('exampleCtrl', exampleCtrl);

然后在HTML标记中,您可以执行以下操作:

<!DOCTYPE html>
<html ng-app="example">
<head>
  <script data-require="angular.js@1.2.14" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>
<body ng-controller="exampleCtrl as example">
  <!-- bind value directly from service -->
  {{example.exampleFn}}
</body>
</html>

这样,您就不需要额外的控制器功能,并且可以将服务数据直接带到标记中。希望这就是你想要的。祝你好运