问题
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