Services reset on logout in Angular

 ̄綄美尐妖づ 提交于 2020-05-17 07:42:46

问题


I have some services in my app which have data that I'd like to reset when the user logs out.

I have a parent component that is only shown when the user is logged in so if I include those services in the providers array of that component decorator, every time the user logs out, this component is destroyed, and the services instances are deleted as well. If another user logs in, this parent component would be created again with new services instances, thus fulfilling my needs.

This works well, but if I use a resolver that needs data from one (or more) of those services instances, how would I inject them? Maybe the idea that I had on resetting those services data is not well thought, and should use an alternative, but I find it really clean and seamless, since when I need to include another service that has data that needs to be reset on logout I would only have to add it to the parent component providers array.

Update: After reading quite a lot of documentation I ended up understanding the different kinds of hierarchical injectors in angular, so I created a new question much more specific. I'll leave this one for reference.


回答1:


You can get a instance of a service using the angular injector:

constructor(private injector:Injector) {
  injector.get(MyService);
}

You might want to look at Dependency injection tokens: Docs



来源:https://stackoverflow.com/questions/61610202/services-reset-on-logout-in-angular

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