ionic 3 - What is the best practice to share variables across the application

五迷三道 提交于 2019-12-02 04:08:57

I would follow the Angular documentation for the Core-feature model. Which means creating a common module for your application wide singleton services (providers). Where you import those services and add them to the providers-list. Then simply import the CoreModule in the AppModule, eg add it to the imports-list.

Core-module:

import { NgModule } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { FooService } from './services/foo-service';
import { BarService } from './services/bar-service';

export {
    FooService,
    BarService
}

@NgModule({
    imports: [ 
        IonicModule
    ],
    providers: [
        FooService,
        BarService
    ]
})
export class CoreModule{}

By adding the

export {
    FooService,
    BarService
}

you can import all the services in your components from one file, like this:

import { FooService, BarService } from '../../core/core-module';

And inject and use them as usual in the constructor:

constructor(private fooService: FooService, private barService:BarService){}

someFunctionCallingServiceFunction(){
    this.fooService.data; // You can access properties
    this.fooService.someFunction(); // and functions 
}

The file structure I use:

--core/
  core.module.ts
  --services/
    foo.service.ts
    bar.service.ts

Example service:

import { Injectable } from '@angular/core';

@Injectable()
export class FooService {
    data:string;
    private hiddenData:string; // Can only be used internally

    constructor(){ }

    someFunction(){
        // Does something...
    }

    // Can only be used internally
    private somePrivateFunction(){
        // Does something else...
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!