如何在单独的文件中贴花常量

时间:2019-02-05 11:52:33

标签: angular

我需要将以下所有这些数据声明到一个单独的常量文件中,并使用ts / controller文件之一

this.flags = {};
    this.flags['NL'] = "flag-icon flag-icon-nl";
    this.flags['BE'] = "flag-icon flag-icon-be";
    this.flags['DE'] = "flag-icon flag-icon-de";
    this.flags['FR'] = "flag-icon flag-icon-fr";
    this.flags['SE'] = "flag-icon flag-icon-se";
    this.flags['ES'] = "flag-icon flag-icon-es";


if(this.routingConfiguratioService.countryCode==='BE'){
      this.labels["ILB"] = "Athlon Car Lease";
      this.labels["DAL"] = "Belfius Auto Lease NV";
      this.labels["C4P"] = "Cars4Publicity BVBA";
    } else if(this.routingConfiguratioService.countryCode==='LU'){
       this.labels["LUX"] = "Athlon Car Lease Lux";
    } else{
       this.labels["ACL"] = "Athlon Car Lease";
       this.labels["WPL"] = "Wagenplan";
    }

3 个答案:

答案 0 :(得分:2)

您可以使用export

data.constant.ts

// You can also simplify your object like this to avoid repetitions by using String Interpolation

const flagIcon = "flag-icon flag-icon-";

export const flags = {
  "NL": `${flagIcon}nl`,
  "BE": `${flagIcon}be`,
  "DE": `${flagIcon}de`,
  "FR": `${flagIcon}fr`,
  "SE": `${flagIcon}se`,
  "ES": `${flagIcon}es`
};

组件

import { flags } from './data.constant'


@Component({...})
export class ChildComponent {

    flagList = flags;    // assign it here or you can console it on your constructor

    constructor() {
       console.log(flags);
       console.log(this.flagList);
    }

}

答案 1 :(得分:1)

要声明常数值,您需要创建单独的constant.ts文件

constant.ts

export const flags {
     static  abc:string = 'ABC'
 }

现在将上面的文件导入组件,并像下面那样访问值

flags.abc;

希望这会有所帮助!

答案 2 :(得分:1)

只需创建如下的const类型:

export const flags = {
  'NL': "flag-icon flag-icon-nl",
  'BE': "flag-icon flag-icon-be",
  'DE': "flag-icon flag-icon-de",
  'FR': "flag-icon flag-icon-fr",
  'SE': "flag-icon flag-icon-se",
  'ES': "flag-icon flag-icon-es",
};

export const labels = {
  "ILB": "Athlon Car Lease",
  "DAL": "Belfius Auto Lease NV",
  "C4P": "Cars4Publicity BVBA",
  "LUX": "Athlon Car Lease Lux",
  "ACL": "Athlon Car Lease",
  "WPL": "Wagenplan",
}

然后将它们导入到您的组件中

import { Component } from '@angular/core';
import { flags, labels } from './flags.const';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  ngOnInit() {
    console.log('flags: ', flags);
    console.log('labels: ', labels);
    /*if(this.routingConfiguratioService.countryCode==='BE'){
      this.labels["ILB"] = "Athlon Car Lease";
      this.labels["DAL"] = "Belfius Auto Lease NV";
      this.labels["C4P"] = "Cars4Publicity BVBA";
    } else if(this.routingConfiguratioService.countryCode==='LU'){
       this.labels["LUX"] = "Athlon Car Lease Lux";
    } else{
       this.labels["ACL"] = "Athlon Car Lease";
       this.labels["WPL"] = "Wagenplan";
    }*/
  }

}

  

这是您推荐的Working Sample StackBlitz