sso*_*nez 12 dependency-injection angular
我正在创建一个项目,我需要一个"常量"类来包含一些配置值.以下是此类的摘录:
export class Constants
{
static Configuration = class
{
static CookieName:string = 'etl_language';
};
...
static View = class
{
static Militaries:string = 'militaries';
static Mutants:string = 'mutants';
static Objects:string = 'objects';
static Scientists:string = 'scientists';
};
}
Run Code Online (Sandbox Code Playgroud)
当我在Angular 2的组件中时,我可以通过导入它来使用该类:
import {Constants} from "../../misc/constants";
Run Code Online (Sandbox Code Playgroud)
然后,只需参考它:
this.cookieName = Constants.Configuration.CookieName;
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我觉得我应该使用Angular 2的依赖注入引擎在构造函数中注入对该类的引用,但它似乎有点矫枉过正.但是,我觉得我违反了做事的"角度方式",所以我不知道我是否可以坚持我的解决方案,或者我是否必须使用DI.
有什么建议?
我可能建议做的是将Constants
类更改为只读属性并Providers[]
从中创建一个类似的属性
@Injectable()
public class ConfigurationConstants() {
private _cookieName:string = 'etl_language';
...
get cookieName():string {
return this._cookieName;
}
...
}
export var CONSTANTS_PROVIDERS:Provider[] = [
provide(ConfigurationConstants, {useClass: ConfigurationConstants}),
provide(ViewConstants, {useClass: ViewConstatns})
];
Run Code Online (Sandbox Code Playgroud)
然后,您可以将这些提供程序引导到应用程序的顶级注入器中,使它们可以在任何您需要的地方使用.
import {CONSTANTS_PROVIDERS} from './constants';
bootstrap(App, [CONSTANTS_PROVIDERS])
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
这是一个演示的插图:http://plnkr.co/edit/RPjDxoIZ8wLY3DDIdhJF
编辑2: Plunker现在回来了,我已经更新了这个例子
编辑: Plunkr现在已经死了所以我无法更新它,但在我的评论中我的意思是这样的(我没有测试过这个,但它应该工作):
public class SubConstants() {
private _someString:string = 'Some String';
...
get someString():string {
return this._someString;
}
...
}
@Injectable()
public class ConfigurationConstants() {
private _cookieName:string = 'etl_language';
private _subConstants:SubConstants = new SubConstants();
...
get cookieName():string {
return this._cookieName;
}
get subConstants():SubConstants {
return this._subConstants;
}
...
}
// ... this would allow you to then do:
confConstants.subConstants.someString
// assuming you injected ConfigurationConstants as confConstants
Run Code Online (Sandbox Code Playgroud)
同样,这是比你对内部类的建议更多的代码,所以它可能取决于你喜欢的.
归档时间: |
|
查看次数: |
19786 次 |
最近记录: |