Angular 最佳实践:在工厂或控制器中承诺? [英] Angular Best practice: promise in a Factory or in a Controller?

查看:19
本文介绍了Angular 最佳实践:在工厂或控制器中承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有一个处理 API 调用的基本工厂.目前我正在使用表单:

I have a basic factory in my app that handles API calls. Currently I'm using the form:

.factory('apiFactory', function($http){

  var url = 'http://192.168.22.8:8001/api/v1/';

  return {
    getReports: function() {
      return $http.get(url+'reports').then(function(result) {
        return result;
      });
    },
    getReport: function(id) {
      return $http.get(url+'report/'+id).then(function(result) {
        return result;
      });
    }
  }
})

在我的控制器中,我像这样处理承诺:

And in my controller I'm handling the promise like so:

.controller('exampleController', function($scope, apiFactory) {

      apiFactory.getReports().then(
        function(answer) {
          if (answer.status==200){
            if (answer.data.status == "error"){
              // DISPLAY ERROR MESSAGE
              console.log(answer.data.msg);
            }
          } else{
            // THROW error
            console.log('error: ', answer);
          }
        },
        function(error){
          console.log('error: ', answer);
        }
      );
    }
  }
})

似乎我可以将承诺处理转移到我的工厂,而不是在我的控制器中进行,但我不确定这是否会比较小的控制器有任何好处.

It seems I could move the promise handling to my Factory instead of doing it in my controller, but I'm not sure if that would have any benefits others than a smaller controller.

有人能解释一下关于这种模式的最佳实践吗?

Could somebody explain the best practices regarding this pattern?

推荐答案

最终取决于您想要向服务调用者提供多少数据.如果需要,您绝对可以将 HTTP 响应对象返回给调用者,并让他们处理响应(顺便说一句,如果承诺已解析而不是被拒绝,则始终是 HTTP 2xx).

It is ultimately up to you how much data you want to provide to the caller of the service. If needed, you could definitely return the HTTP response object to the caller, and have them process the response (which, btw, is always HTTP 2xx, if the promise is resolved rather than rejected).

但是如果您想将调用者与数据如何到达那里的细节隔离开来(也许它被缓存了,或者通过其他机制提供了),并且如果您需要对数据进行后处理,那么建议处理服务中的响应.

But if you want to isolate the caller from the specifics of how the data got there (maybe it was cached, or supplied via another mechanism), and if you need to post-process the data, then it is advisable to handle the response in the service.

这是一个例子:

.factory("apiService", function($http, $q){
  var url = 'http://192.168.22.8:8001/api/v1/';

  return {
    getReports: function() {
      return $http.get(url+'reports').then(function(result) {
        var data = result.data;

        if (data === "something I don't accept"){
           return $q.reject("Invalid data");
        }

        var processedData = processData(data);
        return processedData;
      })
      .catch(function(err){
         // for example, "re-throw" to "hide" HTTP specifics
         return $q.reject("Data not available");
      })
    },
    // same idea for getReport
  }
});

那么控制器就不需要关心底层机制——它得到的只是数据或拒绝.

Then the controller wouldn't need to care about the underlying mechanism - all it gets is data or a rejection.

.controller('exampleController', function($scope, apiService) {
   apiService.getReports()
     .then(function(reports){
        $scope.reports = reports; // actual reports data
     });
})

题外话:

注意我如何将服务名称从 "apiFactory" 更改为 "apiService".我想指出这一点以消除可能的误解.无论您使用 .factory 还是 .service.value,您获得的可注入内容始终是服务 实例..factory 只是一种如何实例化此服务的机制,因此名称 "apiFactory" 用词不当.这里唯一的工厂"是您使用 .factory 注册的函数(当然可以是匿名的):

Notice how I changed the name of the service from "apiFactory" to "apiService". I wanted to point that out to remove a possible misconception. Whether you use .factory or .service or .value what you get as an injectable is always a service instance. .factory is just a mechanism of how this service is instantiated, so the name "apiFactory" is a misnomer. The only "factory" here is a function that you register with .factory (which could be anonymous, of course):

.factory("fooSvc", function fooSvcFactory(){
   return {
      getFoo: function(){...}
   }
})

这篇关于Angular 最佳实践:在工厂或控制器中承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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