Nathan
Nathan

Reputation: 7865

How can I get return a promise's value from an angular service?

I am using $resource, but can just easily use $http (which ever can make this work for me)...

I'd like a service/factory called User and would like to interact with it like so:

var user = new User()

user.name() // 'Joe User'

But no matter how I try, I can only get a promise from my service object and have to use the .then method to resolve the promise.

Can't I resolve it from within the User service and just send the value from various method calls like .name, .email, etc?

If so, how?

Here is my service object (using CoffeeScript)

'use strict'

class User
  constructor: ($resource) ->
    @$resource = $resource '/api/v1/users/:id'

  current: ->
    @$resource.get(id: 'current').$promise

  name: ->
    # I'd like to call current() here and just get the data.name out of it.


angular.module('myApp').service 'User', ['$resource', User]

Here I've modified the example to illustrate further what I'm confused about:

'use strict'

class User
  constructor: ($resource) ->
    @$resource = $resource '/api/v1/users/:id'

  current: ->
    @user = @$resource.get(id: 'current')
    return @user


angular.module('myApp').service 'User', ['$resource', User]

If I call User.current() I get:

Resource {$promise: Promise, $resolved: false, toJSON: function, $get: function, $save: function…}
  > $promise: Promise
  > $resolved: true
  > user: Object
    > id: 1
    > first_name: "Joe"
    > last_name: "User"
  > __proto__: Resource

So in my mind, I should be able to call User.current().user but when I do, I get undefined

Upvotes: 0

Views: 476

Answers (1)

Shomz
Shomz

Reputation: 37711

But no matter how I try, I can only get a promise from my service object and have to use the .then method to resolve the promise.

That's how promises work.

Since services in Angular are singletons, the good thing is that you don't have to repeat this action. The bad thing is that you have to do it once at some point.

Technically, you could do it on app init, run the fetching and store it into a service variable. Then you'll only need to read that variable from the controllers.

So, you're on a right track, just make sure you initialize that service when the app loads and before the user interaction starts.


If you're in for an out of the box solution, consider keeping such data in a localStorage or sessionStorage, depending on the purpose.

Upvotes: 1

Related Questions