Follow along here with a simple Angular repo on github!

Objects:

User: the object shape we want to share across the application

AppStateService: The state object that we are going to inject into our multiple components.

In the AppStateService we introduce the Subject class from rxjs via the parameter onUserChanges.

Putting it together

Using this structure, any time the user state object is reassigned, it will fire our onUserChanges event.

This code block can be repeated throughout the constructor or ngOnInit() method in any component that you want to share the object with.

Additionally, we can still access the user any time as expected via:

let myUser: User = this.state.user;

That’s it!

Make sure to provide the service in your indivudual modules, or the app.module.ts. More info on providing services. And make sure to inject the service into each of your components you want to access it from: