问题描述
我的应用程序中有一些服务,其中包含我要在用户注销时重置的数据.
I have some services in my app which have data that I'd like to reset when the user logs out.
我有一个父组件,该组件仅在用户登录时显示,因此,如果我将这些服务包括在该组件装饰器的providers数组中,则每次用户注销时,该组件都会被销毁,并且服务实例也将被破坏.也删除了.如果另一个用户登录,则将使用新的服务实例再次创建该父组件,从而满足我的需求.
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.
推荐答案
您可以使用角度注射器获得服务的实例:
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
这篇关于在Angular中注销时重置服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!