ProvideIn singleton service among multiple angular instances
See original GitHub issueWhich @angular/* package(s) are relevant/related to the feature request?
core
Description
Hello team, Right now we do not have a way to have a singleton service among multiple angular instances. This is crucial when implement microfrontends. Let’s say we have shell microfrontend which has service AuthService, the remote angular element microfrontends also should be able to have acess to service in singleton way.
I thought it could be done via providedIn: 'platform'
but it appears that it is intended to be for multiple angular modules. Thanks to comment. So it does not suite this case. If we use providedIn: ‘platform’` the service is gonna be instantiated multiple times in shell and custom angular microfrontend element.
Sample repo for playground: https://github.com/vugar005/youtube-webapp-turborepo/pull/22
Proposed solution
We can propose new key something like provideIn: "true-platform"
to solve this case.
Alternatives considered
No suitable alternatives found so far for dependency injection.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:7 (6 by maintainers)
Top GitHub Comments
This is a cool use case, I wonder if it makes sense for this to be handled by the framework though. Managing a kind of global injector that is tied to the webpage instead of individual angular instances seems like something better handled by a meta framework. I’m unaware of anything that does this. I’ll detail a hack solution below that you can use to achieve this but I do not recommend that you do this in production.
I want to strongly stress that before going down this approach, you should consider if it is necessary for your use case. My understanding is that one of the principles of good micro-frontend design is that each application is independently deployable. To ensure this, it is good to make sure that remote applications do not depend on any runtime data structures created by other remotes or the shell (notice how this can be different than sharing common dependencies). My suggestion is provide a separate instance of your service in your remote. If you need to use services to store data that you want to share from your shell, consider if the remote application that is consuming the data is really a remote, or if it should just be part of the shell.
How to implement hack:
The reason this shouldn’t be done for anything that isn’t experimental is because patching the internals of the platform injector to point to your exposed module injector requires patching private APIs, which could potentially lead to catastrophic breakages when you next update your Angular version (or permanent version locking). There is also the potential of memory leaks if references aren’t cleaned up properly when modules are destroyed.
@vugar005 Have you looked https://github.com/angular/angular/issues/40301?