ionic 3 - 在应用程序中共享变量的最佳实践是什么 [英] ionic 3 - What is the best practice to share variables across the application

查看:20
本文介绍了ionic 3 - 在应用程序中共享变量的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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?

推荐答案

我会遵循 Angular 核心功能模型的文档.这意味着为您的应用程序范围的单例服务(提供者)创建一个通用模块.在哪里导入这些服务并将它们添加到 providers-list.然后只需在 AppModule 中导入 CoreModule,例如将其添加到 imports-list.

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.

核心模块:

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
}

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

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 
}

我使用的文件结构:

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

这篇关于ionic 3 - 在应用程序中共享变量的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆