angular2许多字符串值存储 [英] angular2 many string values storing

查看:58
本文介绍了angular2许多字符串值存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些必须在许多组件中使用的字符串常量值.我不想硬编码或将它们作为字符串写在各个组件中. 在angular2应用程序中维护它们的最佳位置在哪里?

I have some string constant value which has to be used in many components.I dont want to hard code or write them as strings in individual components. Where is the best place to maintain them in an angular2 application?

推荐答案

解决方案之一是将您的字符串放在共享服务中.在需要该属性的每个组件中注入服务.如果您的字符串不是常量,并且字符串值可能会更新(这不是您的情况,我想),则这特别好.

One of the solutions would be to place your string in a shared service. Inject the service in every component that need that property. This is specially good if your string is not a constant and the string value might be updated (but it's not your case, I guess).

另一种方法是声明一个普通"打字稿类* .ts文件,如下所示:

An other way would be to declare a 'plain' typescript class, *.ts file, like so:

export const CONFIG = Object({
    MYSTRING: 'Hello',
...
)}

然后在组件中将其用作(例如):

Then use it in the component as (for example):

  import { CONFIG } from 'shared/config';

  myString = CONFIG.MYSTRING;

将所有常量集中在一个位置是很好的选择.

This is good to group all your constants in a single place.

您还可以选择使用一个常量:

You can also choose to go for a single constant:

export const MyString = "Hello";

,然后您可以像以前一样将其导入组件中.

and then you can import it in your component as the before.

这篇关于angular2许多字符串值存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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