Global Application State in Aurelia

坚强是说给别人听的谎言 提交于 2019-12-10 17:43:20

问题


I'm trying to inject a class to other places in my Aurelia app to share authentication state after login. I'm following this example http://hobbit-on-aurelia.net/appstate/ but it looks like the scope is lost during transitions or they are independent instances. Aurelia's docs says:

By default, the DI container assumes that everything is a singleton instance;

When I set the router doing this.userSession.router = router from app instance, the userSession instance is not updated. this.loggedUser is always undefined from outside.

Here is my plunker: http://plnkr.co/edit/qXtSGx


回答1:


If you assume that the user session is a singleton, then that is the problem. In your example the user session is a view template, which is not a singleton. Those get created (in the current implementation, this may change with caching later) whenever you navigate to a view. They also get destroyed whenever you navigate from the view.

What you want is a standalone class that you inject into the constructor of your view model.

export class MyViewModel {
   static inject = [UserSession];
   constructor(userSession) {
       this.userSession = userSession;
   }
}

This will create a singleton instance, the default behavior, of the service class UserSession. The container will then inject it into the view model when the view is created.



来源:https://stackoverflow.com/questions/31210597/global-application-state-in-aurelia

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