1

I'm building out a service layer in Angular for an existing web app. Moving $http requests and data massaging into Angular custom services. I understand the Dependency Injection part of services but I'm struggling with the success/error and passing that back to the controller.

I see some people using promises with $q. Is there an easier "then()" syntax for the promises if you are doing single REST API calls per service call? Note: The backend is non-standard REST so $resource strategy would not work for me. I'm having trouble telling what the latest recommended way of dealing with promises/callbacks from services. Callback seems simple if all you care about is the success condition. Is there a great recent example app that shows this aspect of services well? or articles?

BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • `success()` and `error()` do not return promises, only `then()` does. Here's an example of two services, one uses `success()`, the other `then()`: http://stackoverflow.com/questions/17416599/should-services-expose-their-asynchronicity The consensus on that question was: use `then()`. – Mark Rajcok Jul 03 '13 at 17:05

2 Answers2

1

I recently wrote a handful of caching services, and I couldn't decide between using deferreds or callbacks. I ended up using the deferreds route, and I love it. Having written the same thing twice, I can definitely say that for the people using your service, the changes are only slight.

In the callbacks, they pass a callback for the continuation.

In the deferreds, they daisy-chain a .then and pass it an anonymous function for the continuation. Very similar.

Since Angular has the ability give special consideration to deferreds, I would recommend using the deferreds.

If you set a scope variable to a deferred, Angular is smart enough to wait until that deferred.promise is resolved. Once it is resolved, Angular will then bind to the variable. It is pretty awesome. I would recommend embracing that.

frosty
  • 21,036
  • 7
  • 52
  • 74
0

I've made a simple plunk that implements a service. getData() here returns a promise, and it's .then() has both success and error handlers. Hope it helps you: http://plnkr.co/edit/xu9HXK4mRqwaZcz9bXZd?p=preview

shubhangi
  • 106
  • 3