angularjs从服务到控制器获取错误消息

时间:2016-02-11 19:58:22

标签: javascript angularjs angularjs-service angularjs-resource

使用REST获取费率的工厂

.factory('rateResource', ['$resource', function ($resource) {
    return $resource('/rates/:currency/:effectiveDate', {
        currency: '@currency',
        effectiveDate: '@effectiveDate'
    });
}])

调用工厂以获取资源并检索费率的服务,如果有的话,也会检错。

 .service('RateService', ['rateResource', '$rootScope',
    function (rateResource, $rootScope) {
        var self = this;

        self.rates = [];

        self.search = function (baseCurrency, effectiveDate) {
            self.rates = [];
            var error = null;
            self.baseCurrency = baseCurrency;
            self.effectiveDate = effectiveDate;
            if (baseCurrency) {
                rateResource.query({currency: baseCurrency, effectiveDate: effectiveDate})
                    .$promise.then(function (rates) {
                        if (rates) {
                            angular.forEach(rates, function (rate) {
                                rate.maintTs = $rootScope.formatTimestampToHHMMSS(rate.maintTs);
                                rate.editable = false;
                                self.rates.push(rate);
                            });
                            self.processing = false;
                        }
                    }, function (response) {
                        self.processing = false;
                        error = 'Processing failed due to '+response.status;
                        console.log(error);
                    })
                return {
                    rates: self.rates,
                    errors: error
                }
            }
        }
    }]);

控制器调用服务以获取费率。

.controller('RateController', ['RateService',
    function (rateService) {
        var self = this;

        self.baseCurrency = rateService.getBaseCurrency();
        self.effectiveDate = rateService.getEffectiveDate();
        self.rates = rateService.getRates();

        //make the call from the controller
        self.search = function () {
            var response = rateService.search(self.baseCurrency, self.effectiveDate.yyyyMMdd());
            self.rateRecords = response.rates;
            self.errors = response.errors;
        }
    }])
承诺履行后,控制器中的费率显示正常。但是,收到错误后,它们不会从服务转移到控制器。 (我更改了REST URL以使服务返回404响应)。我做错了什么?

1 个答案:

答案 0 :(得分:1)

目前您正在从异步函数外部返回异步调用响应,您不应该在技术上这样做。异步代码总是在promise / callback函数内得到响应。

但是在你的情况下它是有效的,因为你正在返回带有它的对象引用。如果您查看下面的代码,return语句已经带有self.rates对象引用,那么即使它是空白也会返回,一旦self.rates被填满,它将获得更新值。那么您不必担心rates更新。但是错误的同样的事情是行不通的,因为它是datatype的原始var error = null,所以当你返回值时它会是null(因为异步响应还没有完成)。 / p>

return {
     rates: self.rates, //passed by reference
     errors: error //passed by primitive type
}

因此,为了解决此问题,您还可以将错误设置为object类型,以便它与参考对象一起传递,例如var errors = []&发生错误时使用.push

将错误消息推送到该数组中

但我不推荐以上方式去,我宁愿使用promise模式并保持正确的代码调用堆栈。基本上,你需要从search方法&然后将.then函数等待,直到解决该函数。

<强>服务

.service('RateService', ['rateResource', '$rootScope',
    function(rateResource, $rootScope) {
      var self = this;
      self.rates = [];
      self.search = function(baseCurrency, effectiveDate) {
        self.rates = [];
        var error = null;
        self.baseCurrency = baseCurrency;
        self.effectiveDate = effectiveDate;
        if (baseCurrency) {
          return rateResource.query({
            currency: baseCurrency,
            effectiveDate: effectiveDate
          })
            .$promise.then(function(rates) {
            if (rates) {
              angular.forEach(rates, function(rate) {
                rate.maintTs = $rootScope.formatTimestampToHHMMSS(rate.maintTs);
                rate.editable = false;
                self.rates.push(rate);
              });
              self.processing = false;
            }
            //returning object from promise
            return {
              rates: self.rates,
              errors: error
            }
          }, function(response) {
            self.processing = false;
            error = 'Processing failed due to ' + response.status;
            console.log(error);
            //returning object from promise
            return {
              rates: self.rates,
              errors: error
            }
          })
        }
      }
    }
])

<强>控制器

//make the call from the controller
self.search = function() {
  var response = rateService.search(self.baseCurrency, self.effectiveDate.yyyyMMdd()).then(function() {
    self.rateRecords = response.rates;
    self.errors = response.errors;
  });
}