2

Return an angular $resource from a factory after an asynchronous function call.

Below shows an example of an angular factory in which I'm attempting to return a $resource.

I'm trying to make an asynchronous function call using another service to receive the web service path before returning the $resource.

Is this possible?

angular.module('app').factory('newService', function($resource, configService) {
    configService.get(function(config) {
         return $resource(config.webServicePath + '/api/names', {},
             { 'update': { method:'PUT' } }
         );
    });
});

Would anybody have an example of either a service, provider, or factory returning a resource after an asynchronous function call to receive information like above.

It would also be helpful if you could provide an example of the newService being used in a controller.

Thanks in advance for the help.

1
  • "return" and "asynchronous" don't usually mix. You want to be working with promises, and callbacks. Angular has a service named $q, see docs.angularjs.org/api/ng/service/$q. Most angular requests return promises already. Commented Feb 27, 2014 at 1:08

1 Answer 1

3

currently, it's the callback that's returning the resource, which doesn't help you much. You can't delay a return statement until an async function has completed, but you can work with $q promise.

ngular.module('app').factory('newService', function($resource, configService, $q) {
    var resourcePromise = $q.defer();
    configService.get(function(config) {
        resourcePromise.resolve($resource(config.webServicePath + '/api/names', {},
            { 'update': { method:'PUT' } }
        ));
    });
    return resourcePromise.promise;
});

Here's how $q works

  1. You need to return a value that you get in the future, so you defer it using $q.defer()
  2. This returns a deferred object.
  3. You make your async call, and in its success callback, you call .resolve on the deferred object.
  4. If the callback fails, you call .rejecton the deferred object.
  5. You return deferredobject.promise, which is a promise object.

Using a service that returns promises

When you expect a value from a promise, you can listen for it by passing a callback to its thenmethod. If the promise might be rejected (the operation failed), it's a good idea to pass a second callback, which will be called when the promise is rejected.

Here's a simple example of a service that returns a promise, and how to use it:

http://jsfiddle.net/rP5Gh/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.