How to define variables in ionic


#1

Hi every one

I want to know how can I use variables in ionic2.
For example: in ionic 1 I was use var or scope and rootscope to define variable that can be used in several controllers, in ionic 2 I don’t know how can I define variables that can be use in all application pages or at least one page.

So can u give me example of using public variable and private variable ?


#2

data:any;
if you want specific datatype then you can use.

data: number;
data:string;

hope this will help.


#3

Don’t create global variables. It’s an antipattern at this point.

Learn Typescript and Javascript ES6. This will help you a lot.

For local variables, use let. Don’t use var.

Never give a variable the type any.

For values that multiple pages need, use a provider, and have the pages inject the provider.


#4

Yes I could define the variable but still I can’t change it if i’m open an other page

For exampl: I defined the variable inside “app” ts, but if i’m in home page and try to change the value of variable, its show me an error and i should defined again.


#5

Can u give me a code example for this point for 2 pages ?
Because I searched a lot to understand and did such as u mentioned here but I couldn’t find good examples.


#6

#7

Thank u so much, finally my problem solved by using “provider” :slight_smile: