Angular服务应该返回处理过的数据还是原始数据?

时间:2017-02-04 05:01:57

标签: angularjs angular-services

我正在编写一个服务来通过HTTP请求检索一些数据。

app.controller('WarriorsCtrl', function($scope, warriorService) {
  warriorService.getWarriors(function(warriors){
    $scope.warriors = warriors;
  });
});

app.factory('warriorService', function($http) {
  var getWarriors = function(callbackFn) {
    $http.get('/api/warriors').success(function(data) {
      callbackFn(data);
    });
  };

  return {
    getWarriors: getWarriors
  };
});

如果控制器需要某种处理格式的“战士”,那么在服务本身进行处理是一种好习惯吗?

例如:

var getWarriors = function(callbackFn) {
    $http.get('/api/warriors').success(function(data) {
      var processedWarriors = processData(data);    
      callbackFn(processedWarriors);
    });
};

或者使用该服务返回原始数据并在其他地方(如过滤器)进行处理是否更好?

2 个答案:

答案 0 :(得分:2)

AngularJS $ http服务使用promises来避免Callback Hell

避免回调,而是返回promises,并根据需要使用.then方法处理数据。

app.factory('warriorService', function($http) {
  var getWarriors = function() {
    //vvvv RETURN promise
    return $http.get('/api/warriors').then(function onSuccess(response) {
        var data = response.data;
        var warriors = fn(data);
        return warriors;
    });
  };

  return {
    getWarriors: getWarriors
  };
});

通过将值返回到成功处理程序,.then方法会创建一个新的派生承诺,该承诺将使用已处理的值进行解析。

在控制器中:

app.controller('WarriorsCtrl', function($scope, warriorService) {
  warriorService.getWarriors
   .then (function(warriors){
      $scope.warriors = warriors;
  }).catch(function(errorResponse) {
      console.log(errorResponse.status);
      //throw to chain rejection
      throw errorResponse;
  });
});

除了避免回调地狱之外,promise还保留了以后可以轻松使用的错误信息。

  

因为调用promise的.then方法会返回一个新的派生promise,所以很容易创建一个promise链。可以创建任何长度的链,并且由于可以使用另一个承诺(将进一步推迟其解析)来解决承诺,因此可以在链中的任何点暂停/推迟承诺的解析。这使得实现强大的API成为可能。

     

-- AngularJS $q Service API Reference - Chaining Promises

答案 1 :(得分:0)

It is a good practice to do the processing in the service itself
Avoid using filters for scanning all properties of a complex object graph. 
Use filters for select properties,as Filters can easily be abused and negatively effect performance if not used wisely, for example when a filter hits a large and deep object graph.
相关问题