离子3 - 在整个应用程序中共享变量的最佳实践是什么

时间:2017-07-30 20:21:17

标签: angular typescript ionic3

对于离子3 - 在整个应用程序中共享变量的最佳做法是什么? 例如,如果我有一个通用变量或通用数组,并且我希望它可以在应用程序中的所有源文件中使用,那么最好的方法是什么?

我应该使用提供程序并创建getter函数,还是有更好更简单的方法,比如c中的头文件?

1 个答案:

答案 0 :(得分:4)

我会遵循Angular documentation来获取Core-feature模型。这意味着为您的应用程序范围的单件服务(提供者)创建一个通用模块。导入这些服务并将其添加到providers列表的位置。 然后只需导入CoreModule中的AppModule,例如将其添加到imports列表中。

<强>核心模块:

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

添加

export {
    FooService,
    BarService
}

您可以从一个文件导入组件中的所有服务,如下所示:

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

并像往常一样在constructor

中注入和使用它们
constructor(private fooService: FooService, private barService:BarService){}

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

我使用的文件结构:

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

示例服务:

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