What would be the best way to store data that I can access across an entire app in Angular 2 and Ionic 2 - typescript.
For user information my initial thought was to just import the User class in every file its needed, but since all I require from there is a user ID I thought it'd be better to have some kind of config file, maybe the App class - and I could store environment information as well and urls ect.
I actually have no idea what the best practice around this is and couldn't find much on the topic.
Using a provider to hold global data is working for me in Ionic 2 beta 6, and I believe it is the recommended practice in Angular 2.
Generate a provider from the command line:
ionic g provider GlobalService
Notice how the generated service is decorated with@Injectable
Inject your service in the
@App
class; you do this by declaring it in the providers array:This will create an single instance of your provider that is accesible on every page. Wherever you need to use it, do not declare in the providers array, but on the constructor of the Page:
One way to do it would be to make class with all the properties that you need and configure as a singleton when you bootstrap the application.
Service:
Bootstraping:
Usage:
In the official Ionic 2 forum I found that you should
This is because Ionic doesn't use the same process as Angular 2 for bootstrapping your app, and the @App decorator doesn't provide the ability to create singleton services that are automatically available to all pages and components in your application; therefore the logical use is to inject your service in both your App.ts and the Page in which you are going to use it... Well, this kinda should be the behavior... in my case (I am working with Ionic 2 beta 5) this doesn't work, if you do that and inject @App and your @Page with your service (both importing them and using the providers array, it will create two separate services, which in my case is not so good because I am setting values for my service in App.ts and retrieving those values in some of my pages. So, if you need Singleton behavior, the way to go for me was to create a singleton service using the ol' gang of four pattern this way..
In your Service...
Then wherever you need to use it...
import {Globals} from './services/globals';
globals: Globals;
I have been a little verbose in explaining exactly how I did it because I know that like me, there are lots of developers still getting a grip in Ionic 2 and Angular 2, it costs tons of hours to learn a platform and with issues like this you can literally spend days trying to figure out things, I hope this solution work for you and btw, I know that it may be obsolete by now since Ionic 2 Beta 6 was just released, my advise is for you to test both solutions, first the one in the forum and if that one doesn't work, this one worked for me and I hope it may make things work for you as well.