How to Access Data/Variable from One Page to Another


#1

Say i have 2 pages, named one1 (one1Page) and two2 (two2Page).

in one1.ts, i have a variable

public myValue = 3;

How can i access myValue variable from another page which is two2.ts ?

Thank you :slight_smile:


#2

There are different ways depending on what are you trying to achieve - I would suggest you to check out the following topics to see if you’ll find something that works in your case:


#3

Suppose i just want to increment the value of variable myValue through other Page.

this.myValue++;

Can you just point out one way i should choose, please ?
Thanks!


#4

try state params Pass data with $state.go


#5

You can do it this way:

First, create a new class. Example:

export class MyClass{

    constructor() {
        this.myValue = 0;
    }

    getMyValue() {
        return this.myValue;
    }

    incrementMyValue(){
        this.myValue++;
   }
}

Then, in app.js add it as a provider:

import {MyClass} from 'path/to/file';

@App({
  templateUrl: 'build/app.html',
  // http://ionicframework.com/docs/v2/api/config/Config/
  config: {},
  providers: [MyClass]
})

and add it to the constructor in app.js (at the relevant position. The example I’m showing is assuming the constructor has no other arguments)

constructor(myClassVariable){
    this.myClassVariable = myClassVariable;
}

Now, after this setup, in order to use it in a Page, do this:

@Page({
  templateUrl: 'build/pages/path/to/page'
})
export class MyPage{
    static get parameters() {
        return [
                [MyClass]
        ];
   }

   constructor(myClassVariable) {
    this.myClassVariable = myClassVariable;
   }
}

This way you will inject the provider and everything will work.


#6

What is myClassVariable in your example ?


#7

It is a variable which gets injected with MyClass.


#8

YESS! I did it!

Using service from this link Sharing objects between components, pages

Thanks @iignatov


#9

Ok, great, I’m glad you figured it out. :slight_smile:


#10

Literally same thing as what I suggested. Glad you figured it out in the end :slight_smile: