2

I encountered this pattern in the book 'Mean Machine'.

Until now, I thought you always return a promise from a service (to a controller), then you deal with .success or .then in your controller.

Here, the author is returning the returned data from the promise.

Is this common? Is it recommended practice?

  .factory('Auth', function($http, $q, AuthToken) {

        var authFactory = {};

        authFactory.login = function(username, password) {
            return
                $http
                    .post('/api/authenticate', {
                        username: username,
                        password: password
                    })
                    .success(function(data) {
                        AuthToken.setToken(data.token);
                        return data;
                    });
        };
        ...
scniro
  • 16,844
  • 8
  • 62
  • 106
dwilbank
  • 2,470
  • 2
  • 26
  • 37
  • What does `.success` return? – Thilo Mar 15 '16 at 03:30
  • a token - a big long string – dwilbank Mar 15 '16 at 03:33
  • 1
    No, that is what the function in `.success` will be called with. `.success` itself returns the original promise (the one returned from `.post`). – Thilo Mar 15 '16 at 03:35
  • ah - so the controller (which I haven't seen yet) might chain something like '.finally' to the end of that promise... I forgot about the chaining... – dwilbank Mar 15 '16 at 03:36
  • So you can still call `.then` on the promise returned from `.login`. I don't know what the point is to `return data` from the success handler. It seems to be discarded. – Thilo Mar 15 '16 at 03:37
  • 5
    There's no reason you cannot handle the return value from the promise in the service, especially if it isn't something that needs to be put on `$scope` in a controller. And btw, the [`.success()` and `.error()` methods have been deprecated](https://code.angularjs.org/1.4.8/docs/api/ng/service/$http), so you should use the `promise().then(function successCallback() {}, function errorCallback() {});` pattern. – Bennett Adams Mar 15 '16 at 03:38
  • now that I remember promises can be chained, it makes more sense. Thx sir Thilo – dwilbank Mar 15 '16 at 03:39
  • thx Mr Bennett Adams too. Good info to know as well. – dwilbank Mar 15 '16 at 03:40

1 Answers1

1

Yes, I would recommend such a solution and consider it a good practice. In @scniro response you would need to specially handle error response as well which adds on complexity. Your solution is much cleaner, shorter, and easier to read. I have found a good article about it here http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

Krym
  • 743
  • 6
  • 16