angular2存储多个字符串值

angular2存储多个字符串值,angular,typescript,Angular,Typescript,我有一些字符串常量值,必须在许多组件中使用。我不想硬编码或将它们作为字符串写入单个组件中。 angular2应用程序中维护它们的最佳位置在哪里?angularJs 1中没有常量或配置之类的东西 所以我想做一个飞机班,把你所有的绳子都放在那里。您可以将它们设置为静态,以便直接使用类名访问它们 export class StngsValue { static finrstWord = 'this is test string'; static secoundWord = 'this is t

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

angularJs 1中没有常量或配置之类的东西

所以我想做一个飞机班,把你所有的绳子都放在那里。您可以将它们设置为静态,以便直接使用类名访问它们

export class StngsValue {
  static finrstWord = 'this is test string';
  static secoundWord = 'this is test string';
  static thirdWord = 'this is test string';
}
或者,您可以将所有字符串放在一个json文件中,并从类似这样的角度服务调用该josn文件

@Injectable()
export class ConfigService {
  public config: any;
  private configObs: Observable<any>;

  constructor(private http: Http) {
   }

  public load(): Observable<any> {
    if ( this.config ) {
      return Observable.of(this.config);
    } else {
      this.configObs = this.http.get('/configuration.json').map((res) => {
        this.config = this.config || res.json() || {};
        return this.config;
      });
    }

    return this.configObs;
  }
}
@Injectable()
导出类配置服务{
公共配置:任意;
私有配置对象:可观察;
构造函数(专用http:http){
}
公共负载():可观察{
如果(this.config){
返回可观察的(this.config);
}否则{
this.configObs=this.http.get('/configuration.json').map((res)=>{
this.config=this.config | | res.json()| |{};
返回this.config;
});
}
返回此.configObs;
}
}

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

另一种方法是声明一个“普通”类型脚本类*.ts文件,如下所示:

export const CONFIG = Object({
    MYSTRING: 'Hello',
...
)}
然后在组件中使用它(例如):

这对于将所有常量组合在一个位置是很好的

您也可以选择使用单个常量:

export const MyString = "Hello";

然后您可以像以前一样将其导入组件。

您可以使用共享服务,并将其设置为单例,以便您的所有组件都能够从该服务访问数据/方法/etc。所以您只需将文件声明为

shared.service.ts
内部:

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService{

  public str: string;

}
在app.module.ts中导入服务,在@ngModule中,在providers中添加:

providers: [ SharedService ]
然后在任何组件中,只需导入服务,并在组件构造函数中添加:

constructor(public service: SharedService){}
在这里,您将服务注入组件,您可以阅读关于依赖注入的内容

现在,您可以使用
this.service.string

constructor(public service: SharedService){}