如何通过promise从服务中的函数回调向控制器返回值

时间:2015-06-20 17:57:34

标签: angularjs asynchronous angularjs-service

我正在整理一个简单的电子邮件发件人功能(是的,我知道我不应该把它放在我的前端,这只是一个测试)。该功能有效,但我需要将状态消息返回给我的控制器,这样一旦电子邮件被发送/拒绝,我就可以在我的页面上显示它。

我一直试图让它工作几个小时,但我缺乏适当的知识与回调/承诺合作使我失望所以我需要一些指导。我如何修改下面的代码,以便控制器可以访问状态消息?

core.service('email', ['$q', 'fetchContent', function($q, fetchContent) {

  return {
    sendEmail: function(info) {

      // Fetch token and recipient info from JSON file
      var getEmailInfo = fetchContent.getEmailInfo();

      getEmailInfo.then(function(res) {

        // Access the token and recipient from the JSON file we just requested
        var token = res.data.email.key,
            recipient = res.data.email.recipient;

        // Create a new mandrill instance and set the params
        var emailProvider = new mandrill.Mandrill(token),
            params = {
              "message": {
                "from_email": info.sender,
                "to":[
                  { "email": recipient }
                ],
                "subject": info.company,
                "text": info.message
              }
            };

        // Return a deferred promise containing our status message
        var deferred = $q.defer();

        emailProvider.messages.send(params, function(res) {
          deferred.resolve('Success message');

        }, function(err) {
          deferred.reject('Error message');
        })

        return deferred.promise;
      });
    }
  }
}]);

然后从我的控制器中我想从我服务中的sendEmail函数接收状态消息,无论是成功还是错误:

$scope.send = function(data) {

  var validate = validation.validateEmail(data);

  validate.then(function(res) {

    if (res !== true) {
      $scope.error = res;
    }
    else {
      var status = email.sendEmail(data);
      console.log(status); // Always becomes undefined now
    }
  });
}

1 个答案:

答案 0 :(得分:1)

在您的服务中,使用deferred.resolve()在控制器的.then()方法中调用success函数。

<强>服务

(\d)\1\1

<强>控制器

core.service('email', ['$q', 'fetchContent', function($q, fetchContent) {

  return {
    sendEmail: function(info) {

      // Fetch token and recipient info from JSON file
      var getEmailInfo = fetchContent.getEmailInfo();

      getEmailInfo.then(function(res) {

        // Access the token and recipient from the JSON file we just requested
        var token = res.data.email.key,
            recipient = res.data.email.recipient;

        // Create a new mandrill instance and set the params
        var emailProvider = new mandrill.Mandrill(token),
            params = {
              "message": {
                "from_email": info.sender,
                "to":[
                  { "email": recipient }
                ],
                "subject": info.company,
                "text": info.message
              }
            };

        // Return a deferred promise containing our status message
        var deferred = $q.defer();

        emailProvider.messages.send(params, function(res) {
            deferred.resolve('Success message');

        }, function(err) {
            deferred.reject('Error message');

        })

        return deferred.promise;
      });
    }
  }
}]);