如何声明在单独的文件中的常量

问题描述 投票:0回答:3

我需要所有这些数据如下声明成一个单独的恒定文件并使用它TS的一个/控制器文件

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";
    }
angular
3个回答
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
投票

只要创建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


1
投票

要声明的恒定值,你需要创建单独的constant.ts文件

constant.ts

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

现在,上面的文件导入组件和访问值象下面

flags.abc;

希望这将有助于!

© www.soinside.com 2019 - 2024. All rights reserved.