Ionic 3 - setup global variables from server side data on first app load

I'm working on ionic 3 application which requires to load app settings from server before it navigates to the firstPage(Tab1). Basically, i need to load settings while showing the splash screen to the user.

After getting the settings I need to assign to a global variable/object, so that I can use it in the application without reloading the settings in each and every tab change.

Note: If the user kills the app and re-launch, I want to load the settings again before going to the FirstPage(Tab1).

Which is the best place and the event to handle this operation? Any suggestion?

2 answers

  • answered 2018-05-16 06:08 Pradnya Sinalkar

    You can do that in app.component.ts, may be in initialize() function, called in a constructor. The function may be like:

    protected initializeApp() {   
        this.platform.ready().then(() => {
          //Your code
         });
    }
    

  • answered 2018-05-16 08:57 Mario Padilla

    All this is a theoretical example so you will have to create your own code

    You can use APP_INITIALIZER from Angular core Example

    app.module.ts

    import { APP_INITIALIZER } from "@angular/core";
    import { GlobalProvider} from "../providers/global/global";
    
    export function init_app(global: GlobalProvider){
        // Init required providers before load the app
        // NOTE: this factory needs to return a function (that then returns a promise)
        return () => global.load()  // + any other providers...
    }
    
    @NgModule({
      ...
      providers: [
        GlobalProvider,
        {
          provide: APP_INITIALIZER,
          useFactory: init_app,
          deps: [GlobalProvider],
          multi: true
        },
        ....
      ]
    })
    

    Create a provider: ionic g provider global Example

    Declare your variables in a new Provider

     import { Injectable } from '@angular/core';
        /*
          Generated class for the GlobalProvider provider.
        */
        @Injectable()
        export class GlobalProvider {
    
          public myGlobalVar: string;
    
          public async load() { ... }
    
        }
    

    Use this in other .ts files like below

    import { GlobalProvider } from "../../providers/global/global";
    
    constructor( public global: GlobalProvider) { }
    

    Use in template file like below

    <ion-content>
      <h1>{{ global.myGlobalVar }} </h1>
    </ion-content>