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

ε祈祈猫儿з 提交于 2019-12-02 12:54:02

问题


For ionic 3 - what is the best practice to share variables across the application? For example, if I have a generic variable or generic array and I want it to be available across all source files in the application, what is the best way to do it?

Should I use a provider and create getter functions or maybe there is some better and simple way to do it, such like header files in c?


回答1:


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...
    }
}


来源:https://stackoverflow.com/questions/45404305/ionic-3-what-is-the-best-practice-to-share-variables-across-the-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!