Where in Ember to make initial session status XHR to server

此生再无相见时 提交于 2019-12-12 02:55:50

问题


When my ember application starts, I need to make a call to the server to check on the current session/user status. This needs to happen before any model hooks are run or any templates are rendered.

Where should this happen? I can't find quite the right place -- it keeps running a bit too late, or not at all. Right now I have it in my application route init with this._super.apply(), which works ok but it runs after child route model hooks.

I would think it should be an initializer, but the ember-cli docs specifically state that initializers should not contain XHR's (it states this under the generators section).

I'm essentially asking where to make the server request mentioned in the answer to this question: How and when to use Ember.Application register and inject methods?


回答1:


Do this in your application route's beforeModel hook. Make sure that the call to check the session/user state returns a RSVP.promise and return this promise in the beforeModel hook. Ember provides the guarantee that execuction will block until this promise resolves/rejects. So redirect on failure/lack of session to your auth route or whatever makes sense or let execution continue as is. The application route is the base route of the application and is entered every single time you refresh the app, including the initial load of the app. Each time subroutes change, the application route is not reentered and this hook will not be called. But if you are in a subroute and hit refresh, the application route will be entered and all hooks executed. Depending on your needs, you might also need to execute code in the subroute's beforeModel hooks as well. If so, use a mixin or make all subroutes extend from a common base route that handles this functionality




回答2:


After you create the ember app, you can call the deferReadiness() method and after this make your xhr call, on success then you call advanceReadiness()

This way the application wont continue to start until you xhr call is completed.

You can check more at the docs - http://emberjs.com/api/classes/Ember.Application.html#method_deferReadiness



来源:https://stackoverflow.com/questions/30306080/where-in-ember-to-make-initial-session-status-xhr-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!