Aurelia的全球申请国 [英] Global Application State in Aurelia
问题描述
我试图在我的Aurelia应用程序中的其他地方注入一个类,以便在登录后共享身份验证状态.我正在按照此示例 http://hobbit-on-aurelia.net/appstate/但看起来范围在过渡期间丢失了,或者它们是独立的实例. Aurelia的文档说:
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:
默认情况下,DI容器假定一切都是单例 实例;
By default, the DI container assumes that everything is a singleton instance;
当我将路由器设置为从应用实例执行this.userSession.router = router
时,不会更新userSession实例. this.loggedUser
始终是从外部未定义的.
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.
这是我的朋克: http://plnkr.co/edit/qXtSGx
推荐答案
如果您假设用户会话是单例用户,那就是问题所在.在您的示例中,用户会话是视图模板,而不是单例.每当您导航到视图时,它们都会被创建(在当前实现中,此情况可能会在以后进行缓存更改).每当您从视图导航时,它们也会被破坏.
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;
}
}
这将创建服务类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.
这篇关于Aurelia的全球申请国的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!