Angular-从Factory方法检索数据的最佳实践 [英] Angular - Best practice for retrieving data from a Factory method

查看:86
本文介绍了Angular-从Factory方法检索数据的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些有关从本地JSON文件检索数据和处理响应的最佳方法的信息.浏览完Stack Overflow之后,我有不同的想法,因为我已经看到了做同一件事的多种方式(尽管没有解释为什么可能会或可能不会有人选择它的原因.)

I'm looking for some information on the best way to retrieve data from a local JSON file and handle the response. After browsing through Stack Overflow, I have some mixed thoughts as I've seen multiple ways of doing the same thing (although no explanation on why one may or may not be preferred).

从本质上讲,我有一个Angular应用程序,该应用程序利用工厂从JSON文件中检索数据.然后,我等待响应在控制器中解析,然后再在html文件中使用它,类似于以下内容:

Essentially, I have an Angular app that is utilising a factory to retrieve data from a JSON file; I'm then waiting for the response to resolve in my controller before using it in my html file, similar to the below:

工厂:

comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';

return {
 retrieveInfo: function() {
  return $http.get(retrievalFile);
 }
}

}]);

控制器:

comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {

Info.retrieveInfo().then(function(response) {
  $scope.info = response.data;
});

}]);

我的主要争论点是弄清楚什么时候最好等待响应解决,甚至是否重要.我想让工厂返回已兑现的承诺,并等待控制器也检索数据.我认为,最好将所有数据检索从控制器中提取到工厂中,但是我不确定这是否扩展到等待工厂内部返回实际数据.考虑到这一点,我对于是选择选项1还是选择选项2感到困惑,并且真的很感谢经验丰富/合格的开发人员的一些反馈!

My main point of contention is figuring out when it's best to wait for the response to resolve, or if it even matters. I'm toying with the idea of having the factory return the fulfilled promise, and wait for the controller to retrieve the data also. In my view, it's best to abstract all data retrieval out of the controller and into the factory, but I'm not sure if this extends to waiting for the actual data to be returned within the factory itself. With this in mind, I'm confused about whether to opt for option 1 or option 2 and would really appreciate some feedback from more experienced/qualified developers!

工厂:

comparison.factory('Info', ['$http', function($http) {
var retrievalFile = 'retrievalFile.json';

return {
  retrieveInfo: function() {
    return $http.get(retrievalFile).then(function(response) {
      return response.data;
    });
  }
}

}]);

控制器:

comparison.controller('comparisonController', ['$scope', 'Info', function($scope, Info) {

Info.retrieveInfo().then(function(response) {
  $scope.info = response;
});

}]);

谢谢您的任何输入/建议!

Thank you for any input/suggestions in advance!

推荐答案

这取决于您的控制器期望什么以及如何设置应用程序.通常,我总是选择第二种方法.这是因为我通常在所有api请求中都具有全局错误或成功处理程序,并且具有共享的api service.像下面这样.

It depends on what your controller is expecting and how you set up your application. Generally, I always go with the second option. Its because I usually have global error or success handlers in all api requests and I have a shared api service. Something like below.

var app = angular.module('app', []);

app.service('ApiService', ['$http', function($http) {
    var get = function(url, params) {
    $http.get(url, { params: params })
        .then(handleSuccess, handleError);
  };

  // handle your global errors here
  // implementation will vary based upon how you handle error
  var handleError = function(response) {
    return $q.reject(response);
  };

  // handle your success here
  // you can return response.data or response based upon what you want
  var handleSuccess = function(response) {
    return response.data;
  };
}]);

app.service('InfoService', ['ApiService', function(ApiService) {
    var retrieveInfo = function() {
    return ApiService.get(retrievalFile);

    /**
    // or return custom object that your controller is expecting
    return ApiService.get.then(function(data) {
      return new Person(data);
    });
    **//
  };

  // I prefer returning public functions this way
  // as I can just scroll down to the bottom of service 
  // to see all public functions at one place rather than
  // to scroll through the large file
  return { retrieveInfo: retrieveInfo };
}]);

app.controller('InfoController', ['InfoService', function(InfoService) {
  InfoService.retrieveInfo().then(function(info) {
    $scope.info = info;
  });
}])

或者,如果您使用的是路由器,则可以将数据解析到控制器中. ngRouter和uiRouter支持都可以解决:

Or if you are using router you can resolve the data into the controller. Both ngRouter and uiRouter support resolves:

$stateProvider.state({
    name: 'info',
  url: '/info',
  controller: 'InfoController',
  template: 'some template',
  resolve: {
    // this injects a variable called info in your controller
    // with a resolved promise that you return here
    info: ['InfoService', function(InfoService) {
        return InfoService.retrieveInfo();
    }]
  }
});

// and your controller will be like
// much cleaner right
app.controller('InfoController', ['info', function(info) {
    $scope.info = info;
}]);

这篇关于Angular-从Factory方法检索数据的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆