简体   繁体   中英

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. 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.

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.

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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