简体   繁体   English

AngularJS服务并承诺最佳实践

[英]AngularJS services and promises best practice

I have an AngularJS application where I have service s that calls $http resource and returns a promise that I resolve in my controller. 我有一个AngularJS应用程序,我有service s调用$http资源并返回我在控制器中解析的promise Here's a sample of what I'm doing: 以下是我正在做的一个示例:

app.service('Blog', function($http, $q) {
  var deferred = $q.defer();
  $http.get('http://blog.com/sampleblog')
    .then(function(res) {
        // data massaging stuffs
      return deferred.resolve(res.data);
    }, function(err) {
        // may be some error message checking and beautifying error message
      return deferred.reject(err);
    });
    // chain if further more HTTP calls
  return deferred.promise;
});

But I could simply do the following as well: 但我也可以简单地做以下事情:

app.service('Blog', function($http) {
  return $http.get('http://blog.com/sampleblog');
});

And then do the validation, error beautifying, chaining promises, etc. at the controller level. 然后在controller级别进行验证,错误美化,链接承诺等。

My question is : Which is considered as 'best practice', if any, in terms of code resiliency and flexibility? 我的问题是:在代码弹性和灵活性方面,哪个被认为是“最佳实践”? Or is there a better way to do it completely different than this ? 或者有更好的方法来完成与此完全不同的方式吗?

As per the concept behind MVC, controller should decide what to do with the promise. 根据MVC背后的概念,控制器应该决定如何处理承诺。

The service should initiate the promise. 该服务应该发起承诺。

app.service('Blog', function($http) {
  return $http.get('http://blog.com/sampleblog');
});

And the controller should decide what to do when resolved. 并且控制器应该在解决时决定做什么。

$scope.response = Blog;

$scope.response.then(function(response) {
    DataProcessor.processData(response.data)
})
.error(function(error){
    ErrorHandler.handle(error);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM