简体   繁体   English

打字稿AngularJs CommonJs常数

[英]Typescript AngularJs CommonJs Constants

So I have this scenario where I choose a filter object to build. 因此,在这种情况下,我选择要构建的过滤器对象。 The list of filters is stored in an array: 筛选器列表存储在数组中:

app.constant("filters", () => <IFilterList>[
    (value, label) => <IFilterObject>{ value: value, label: label }
]);

interface IFilterList {
    [index:number]: (value?:string, label?:string) => IFilterObject
}

interface IFilterObject {
   value: string,
   label: string
}

This allows the module that sets the filter being used: 这允许设置所用过滤器的模块:

// somemodule.js

app.controller("SomeController", (filters, filterService) => {
    var filter = filters[0]("this value", "this label");

    filterService.change(filter);
});

As you can see doing filters[0] with a magic number is poor to say the least. 如您所见,至少可以说用魔术数字来进行filters[0]是很糟糕的。

In C# I would create a static class which is public so can be used anywhere. 在C#中,我将创建一个公共的静态类,因此可以在任何地方使用。 Something like: 就像是:

public static class FilterNames
{
    public const int NameFilter = 0;
}

How would you do the same in AngularJs and TypeScript using the CommonJs module system? 您将如何使用CommonJs模块系统在AngularJs和TypeScript中做同样的事情?

In my mind you would need global variables... is really the best way to do this? 在我看来,您将需要全局变量……这真的是最好的方法吗?

You could make an enum with the values. 您可以使用值进行枚举。

enum FilterType {
  NAME, 
  AGE
}

Enum's get numeric values by default, so the 1st one gets the value 0, 2nd one value 1, etc. 默认情况下,Enum会获取数字值,因此第一个获取值0,第二个获取值1,依此类推。

You can use it like this: 您可以像这样使用它:

filters[FilterType.NAME]("this value", "this label");

The enum can be in another file, and you can import it anywhere you want to use it. 枚举可以在另一个文件中,您可以将其导入任何要使用它的位置。 You can learn more about enums in TypeScript here . 您可以在此处了解有关TypeScript中的枚举的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM