Sharing objects between components, pages

Sorry if i am asking too much of question. Still learning ionic 2 with typescript and some parts i am not sure whether I’m doing right.

With ionic 1, we had $rootScope or even there was a way to access parent objects using $parent.
with ionic 2, what is the best practice to share objects between pages.

In my app.ts, i have a variable “sharedObject” and potentially want to update that object from other Page class.

Below is just an sample code

@App()
class MyAppClass {

   constructor() {
   } 

   updateSharedObject() {
       // need to update sharedObject which is being used in home.ts
   } 
}

In my page class (home.ts),

@Page()
export class HomePage {

   sharedObject: any;
} 

What’s the best way to do this?

using Events subscribe/publish method seems a way to do it, but wasn’t working as expected.

I would say “as infrequently as possible”.

Generally, this sort of thing introduces too much coupling between parts of the app, resulting in unmaintainable and difficult to test spaghetti. That being said,

@App ({
  providers: [ThingyService]
})
export class ThingyService {
  private _thingy: Thingy;

  getThingy(): Thingy {
    return this._thingy;
  }

  setThingy(thingy:Thingy) {
    this._thingy = thingy;
  }
}
@Page()
@Injectable()
export class Page1 {
  constructor(private _thingyService:ThingyService) {
  }

  updateThingy() {
    let thingy = this.acquireNewThingySomehow();
    this._thingyService.setThingy(thingy);
  }
}
@Page({
  template: `looking at {{thingy().foo}}`
})
@Injectable()
export class Page2 {
  constructor(private _thingyService:ThingyService) {
  }

  thingy():Thingy {
    return this._thingyService.getThingy();
  }
}
5 Likes

But setThingy() in Page1 class won’t update the object in realtime in Page2 wouldn’t it? @rapropos

Yes, it would, because there isn’t really a “thingy object” in Page2, there’s a function that gets called over and over again. Yes, there are alternate ways using events or observables to keep various different copies of the same object synchronized, but I think this is the simplest.

i can’t understand how it’s work
case 1)
i have nav menuwhich is shared with all page but when i am login and go to dashboard after login so i can append new list which is log out.

my nav menu bar before login is
1.sign up
2.sign in
3.loan details
4.contact

my nav menu bar after login is
1.loan details
2.contact
3.log out
4.profile

i’ creating global class for global variable
global.ts
@Injectable()
export class Global{
public loginState:boolean = false;
}

i have app.component.ts include

import { Global } from '../global/global';

@Component({
  templateUrl: 'app.html'
})

export class MyApp {
   @ViewChild(Nav) nav: Nav;
   rootPage: any;
   is_login: boolean;
    //rootPage = loginPage;
    // Check if the user has already login
  constructor(public platform: Platform, public storage: Storage, public menu:MenuController,public global:Global) {
 //  this.storage.set('hasLogin', '');
   this.menu.enable(false,'loggedInMenu');
  
    console.log('i m hest',this.storage.get('hasLogin'));
    this.storage.get('hasLogin')
      .then((hasUserLogin) => {
        if (hasUserLogin) {
          this.rootPage = HomePage;
         
        } else {
          this.rootPage = loginPage;
        }
        this.platformReady()
      });
      this.is_login =  global.loginState;
  }
}

app.html include

   <ion-item >Loan Simulator</ion-item>
      <ion-item  (click)="stateChange('loginPage')"> Sign In</ion-item>
      <ion-item (click)="stateChange('signUp')"> Sign Up</ion-item>
      <ion-item> Contact Us</ion-item>
      <ion-item *ngIf="is_login" (click)="logOut()"> Log Out</ion-item>

home.ts include

import { Global } from '../../global/global';
@Component({
    selector: 'home-page',
    templateUrl: 'home.html'
})
export class HomePage{
     @ViewChild(Nav) nav: Nav;
     is_login : boolean = true;
    constructor(public navCtr : NavController,public menu:MenuController,public global:Global){
          global.loginState = this.is_login;
         this.menu.enable(true,'loggedInMenu');
  }
    complaint(){
      this.navCtr.push(userComplaint);  
    }
} 

is_login is not reflect please help me out

I can’t make any sense out of your code, so all I can say is that here is how I handle user state in apps like this.

HI! could you explain what is Thingy in your code ?