0

I am trying to have a service return a promise, but keep getting PushService.initPush.then is not a function

Here is my service:

app.service('PushService', function($log, $q, $ionicPopup) {
return {        
    initPush: function() {
        var deferred = $q.defer();
        MFPPush.initialize (
            function(successResponse) {
                console.log("Successfully intialized push: " + successResponse);
                deferred.resolve();
            },
            function(failureResponse) {
                console.log("Failed to init push: " + JSON.stringify(failureResponse));
                deferred.resolve();
            }
        )
        return deferred;
    }
}
}

And my controller:

PushService.initPush.then(function(response) {
    console.log(response);
})

But am getting PushService.initPush.then is not a function why does this keep happening, to me it looks like I am returning a promise? I have been following this tutorial http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/ and looked at this SO question Processing $http response in service but cant get it to work.

Thanks for the help

Community
  • 1
  • 1
iqueqiorio
  • 1,149
  • 2
  • 35
  • 78

1 Answers1

1

First, you need to call initPush method, not just access its property.

Second, in $q there's a not-so-subtle difference between deferred and promise APIs: the former is about modifying its state, and the second is about deciding what to do when it's settled (resolved or rejected). So you actually need to return deferred.promise (instead of deferred).

Finally, I'd recommend using $q constructor pattern instead, like shown in the doc:

initPush: function() {
  return $q(function(resolve, reject) {
    MFPPush.initialize(
      function(successResponse) {
        console.log("Successfully intialized push: " + successResponse);
        resolve(successResponse);
      },
      function(failureResponse) {
        console.log("Failed to init push: " + JSON.stringify(failureResponse));
        reject(failureResponse);
      }
    );
  });
}

As a matter of fact, if you don't need logging here, you can write it out as simple as ...

return $q(function(resolve, reject) {
  MFPPush.initialize(resolve, reject);
});
raina77ow
  • 103,633
  • 15
  • 192
  • 229