Ionic 2 - How to manage global variables?

后端 未结 2 1266
借酒劲吻你
借酒劲吻你 2020-12-29 04:02

THE SITUATION:

In my Ionic 2 app i have a simple login which form is contained inside the right menu. You click on the right icon in the header - wi

相关标签:
2条回答
  • 2020-12-29 04:42

    I think you need to define your global variable in a Service (aka Provider).

    Like that:

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class SingletonService {
      public loginState:boolean = false;
    }
    

    Then you declare that service only once in the app.module.ts file:

    ...other imports...
    import { SingletonService } from '../services/singleton/singleton';
    
    @NgModule({
      declarations: [
        MyApp,
        ...
      ],
      imports: [
        IonicModule.forRoot(MyApp)
      ],
      bootstrap: [IonicApp],
      entryComponents: [
        ...
      ],
      providers: [
        ...
        SingletonService
      ]
    })
    export class AppModule {}
    

    On each Ionic page you use, you import the service on top of your page but don't declare it in the @Component part. Since it'll have been declared (or instantiate, not sure about the right vocabulary here) only once with app.module.ts, the value will be global from one page to an other:

    import {Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    
    import { SingletonService } from '../../services/singleton/singleton';
    @Component({
        selector:'my-page',
        templateUrl: 'my-page.html',
    })
    export class MyPage {
        constructor(public navCtrl: NavController,public singleton:SingletonService){} 
    }
    

    Then in your html template (my-page.html here) linked to a specific page (thru the @Component) you put conditional on fields you want to display if singleton.loginState == true.

    0 讨论(0)
  • 2020-12-29 04:55

    In Ionic 3 you can use localStorage to perform this operation Example:

    Page 1

    let page1Data = 'This is Page 1 Data';
    localStorage.setItem('storedData': page1Data);
    

    Page 2

    Use this Data in page 2:

    let page1Data = localStorage.getItem('storedData');
    console.log(page1Data);
    

    For more details: https://answerdone.blogspot.com/2018/03/how-to-store-and-use-data-globally-in.html

    0 讨论(0)
提交回复
热议问题