How can I make a global variable?

I am developing a Music App and for that I have implemented a “MusicService” which loads stuff from the storage, holds the current Queue and so on.

Right now I only have one page, where this Service gets injected in the constructor and I call everything with this.musicService.

Now I want to make a second Page with Playlists, but that needs to have access to the MusicService too.

If I just pass it in the constructor I will have two instances of the service right?

How can I make it that every Page has the same instance of MusicService?

Thanks for any help!

I will provide Code if needed :slight_smile:

If you declare your service only in your main app.module.ts it’s gonna be the same service (singleton) for your all app, for all your pages

providers: [ 
   MusicService
]

doing so, each time you reference it in a constructor, in a page, component or even another provider also declared in app.module.ts, it always gonna be the same service

but important, this works only if you declare it once in app.module.ts. if you would declare it in a submodules when using lazy loading, then the service would exist once for the submodules and not the all app

I hope my explanation is somehow clear, if not let me know

2 Likes

Thanks alot!

Works like a charm :smiley:

1 Like