【问题标题】:angular2 many string values storingangular2 许多字符串值存储
【发布时间】:2017-09-21 17:29:19
【问题描述】:

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

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

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

    然后在组件中使用它作为(例如):

      import { CONFIG } from 'shared/config';
    
      myString = CONFIG.MYSTRING;
    

    最好将所有常量组合在一个地方。

    您也可以选择单个常量:

    export const MyString = "Hello";
    

    然后你可以像以前一样将它导入到你的组件中。

    【讨论】:

      【解决方案2】:

      在 angular 中没有像 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;
        }
      }
      

      【讨论】:

        【解决方案3】:

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

        shared.service.ts
        

        内部:

        import { Injectable } from '@angular/core';
        
        @Injectable()
        export class SharedService{
        
          public str: string;
        
        }
        

        在您的 app.module.ts 中导入服务并在 @ngModule 中,在提供程序中添加:

        providers: [ SharedService ]
        

        然后在您的任何组件中简单地导入服务,并在组件构造函数中添加:

        constructor(public service: SharedService){}
        

        在这里你将服务注入到你的组件中,你可以阅读依赖注入

        现在您可以使用 this.service.string 访问您的字符串

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-13
          • 2018-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多