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