Ionic 4 Global variable for the application


In my ionic app I want to store the application global variables which can be accessed across all the pages. For this I have created an injectable service which I import in app.module.ts file and added it into providers section.

I then inject it into home page and initialise some values in ngOnInit method. In the login page, I authenticate user and set user details into global variable. When there is successful login, I navigate to home page again using router.navigate method. The ngOnInit method of home page is called again and values are reset.

It seems when you inject a service in the constructor, a local variable is created and values set are local. Every page where I want to call it creates a new local instance. Although in constructors of each page, I declare it as public, it seems values are not getting shared across pages.

How can we achieve this? I want one public variable which can be accessible by all pages.



See this.

1 Like

I don’t exacty understand what you want, but in my apps, i have some variables, in a separat file named “constants.ts” with for example:

export const VARIABLE = (whateverhere)

than you can import that variable from every page… :blush:

use session storage, cookies or local storage for user login info.

The point here is that indeed services provided for at top level allow ypu tonaccess the data theoighout all components (singleton), but u should not rely on the oninit lifecycle to run when the route changes. Plse refer to the definition of those hooks at

The prettiest and most versatible approach is to use rxjs patrerns of which the behaviorsubject is the easiest to assure consist and async state management of data across all components

Traversing data throuhj local storage does not solve your lifecycle issue and creates additional overhead on a singleton service fornwhich the angular framework is known for

Basically if u go that route you might as well forget all of angular and any advantages you believe to get from it

Irrespective if technically it isnposible or can be made to work

The link provided gives you the proper code example (by @rapropos)

Enjoy the coding, plse read all of, and hyperjump into angular fun!

Great help!!!

Thanks I used BehaviourSubject and subscribed it in pages where I needed the Global Variables. This solved the issue.