How to access a constant in an Angular 2 component and service?

后端 未结 5 926
你的背包
你的背包 2020-11-28 12:45

I have a constants file constants.ts:

export const C0NST = \"constant\";

I access it in a service some.service.ts<

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 13:10

    Since in the Component's template you can only use attributes of the Component's class, you can't directly use any external constants (or external variables).

    The most elegant way that I've found so far is the following:

    import { MY_CONSTANT } from '../constants';
    
    @Component({
      // ...
    })
    export class MyTestComponent implements OnInit {
    
      readonly MY_CONSTANT = MY_CONSTANT;
    
      // ...
    }
    

    which basically just creates a new attribute MY_CONSTANT inside the component class. Using readonly we make sure that the new attribute cannot be modified.

    Doing so, in your template you can now use:

    {{ MY_CONSTANT }}
    

提交回复
热议问题