离子3 - 在整个应用程序中共享变量的最佳实践是什么 [英] ionic 3 - What is the best practice to share variables across the application
问题描述
对于离子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 文档核心特征模型。这意味着为您的应用程序范围的单件服务(提供者)创建一个通用模块。导入这些服务并将其添加到提供程序
-list的位置。
然后只需在 AppModule
中导入 CoreModule
,例如将其添加到导入
-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';
并像往常一样在构造函数中注入和使用它们
:
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...
}
}
这篇关于离子3 - 在整个应用程序中共享变量的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!