Global application in Aurelia

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

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

When I set up a router running this.userSession.router = router

from an application instance, the userSession instance is not updated. this.loggedUser

always undefined outside.

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

+3


source to share


1 answer


If you think that the user's session is a single one, this is a problem. In your example, the custom session is a view template that is not a single. The ones that get created (in the current implementation, this may change with caching later) whenever you go to the view. They are also destroyed whenever you move out of view.

What you want is a separate 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 UserSession service class. The container will then inject it into the view model when the view is created.

+5


source







All Articles