AngularJS服务并承诺最佳实践 [英] AngularJS services and promises best practice

查看:118
本文介绍了AngularJS服务并承诺最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AngularJS应用程序,我有 service s调用 $ http 资源并返回<$ c我在控制器中解析的$ c> promise 。以下是我正在做的一个示例:

I have an AngularJS application where I have services that calls $http resource and returns a promise that I resolve in my controller. 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');
});

然后在控制器级别。

我的问题是:在代码弹性和灵活性方面,哪个被视为最佳实践?或者有更好的方法来做到与此完全不同吗?

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 ?

推荐答案

根据MVC背后的概念,控制器应该决定什么与承诺有关。

As per the concept behind MVC, controller should decide what to do with 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);
})

这篇关于AngularJS服务并承诺最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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