vendredi 25 novembre 2016

Ember computed property depending on service property not updating

In my Ember 2.8 application, I'm establishing a Websocket connection in a service. The connection URL changes when a user is logged in (it then includes the user auth token as a query parameter).

The current user service is simple:

CurrentUserService = Ember.Service.extend(
  name: "current-user"

  user: null

  load: ->
    // Do some stuff
    @set("user", user)
 )

It works exactly as expected, and I use it to display the current users username on the page (among other things).

In the Websocket service, all I do is create a computed property, depending on currentUser.user, that sets up the connection (depending on whether a user is logged in):

ActionCableService = Ember.Service.extend(
  name: "action-cable"

  cable: service()
  currentUser: service()

  testObs: Ember.observer("currentUser", ->
    console.log "currentUser changed, #{ @get("currentUser.user") }"
  )

  consumer: Ember.computed("currentUser.user", ->
     consumerUrl = "ws://localhost:10000/cable"

    if @get("currentUser").user?
      consumerUrl += "?token=#{ @get("currentUser.user.authToken") }"

    console.log(consumerUrl)
    return @get("cable").createConsumer(consumerUrl)
  ) 
)

Problem is, the consumer property never gets updated. It's set once, on page load, and when the user property of the currentUser service changes, consumer is not updated, and neither does my test observer.

When I refresh the page, sometimes the logged in consumerUrl is used, and sometimes it's not.
I'm guessing sometimes the session restoration happens first, and sometimes the action cable service happens first.

What I expected to happen when the action cable service gets loaded first is:

  1. Action cable service gets loaded, no current user set yet, connect to public websocket
  2. Logic that handles restoring user from session data fires, sets currentUser.user (this happens, I can see the username on my page)
  3. The consumer computed property notices the currentUser.user change and connects to the private consumerUrl (does not happen)

I can very easily solve this problem in a way that does not depend on computed properties, but I would like to know what went wrong here.




Aucun commentaire:

Enregistrer un commentaire