0

I am using AngularJs with Coffee-Script, and I have a requirement to pass the current login username to the backend service in header which means I have to retrieve the username through another request. However the $resource service to perform REST request in AngularJs seems to be async, so I can't get the username though the following code:

'use strict'

angular.module('testapp.service').factory 'TestController', [

  '$resource', 'userService'
  ($resource, userService) ->
    userService.getUser().then (user) ->
      console.log(user.name) # <- line 8
      username = user.name # <- line 9
    $resource "/api/path", {},
      get:
        method: 'GET'
        headers:
          'username': username
]

With line 8, I could get the username printed to the console. With line 9, I can't pass it to the headers field below.

Every time, when the page refreshed, the console get printed the username, but when I click on the button, there is no printing again. Please help, any kind of suggestion would be helpful and appreciated !

I am using AngularJs 1.4

ponypaver
  • 397
  • 1
  • 2
  • 14

1 Answers1

0

Wait to make the $resource request until the getUser() promise is resolved.

EDIT:

Before you call TestController.get, get the user. When the promise to getUser() is resolved, send the username as a parameter, and have your $resource.get wrapped in another function like they have here:

How to pass headers on the fly to $resource for angularjs

angular.module('testapp.service').factory 'TestController', [

  '$resource'
  ($resource) ->
    getWhatevs: (username) ->
        return  $resource "/api/path", {},
          get:
            method: 'GET'
            headers:
              'username': username
    }
};


/* The caller */
userService.getUser().then (user) ->
    console.log(user.name) # <- line 8
    username = user.name # <- line 9
    
    TestController.getWhatevs(username).get()

By the way, TestController is a factory and not a controller.

Community
  • 1
  • 1
mikeorr85
  • 471
  • 5
  • 13
  • No, this is not working. It reports TestController.get is not a function :( – ponypaver Mar 09 '17 at 15:10
  • Yes, that was a bad snippet. I removed it and linked you to a better example – mikeorr85 Mar 09 '17 at 15:50
  • the solution above is working, but I don't want to call it like TestController.getWhatevs(username).get(), I want to call it like TestController.get() or TestController.get(username), is this possible ? – ponypaver Mar 12 '17 at 09:05