如何在Angular 2组件和服务中访问常量? [英] How to access a constant in an Angular 2 component and service?

查看:88
本文介绍了如何在Angular 2组件和服务中访问常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常量文件 constants.ts :

export const C0NST = "constant";

我在服务 some.service.ts 中访问它,如下所示:

I access it in a service some.service.ts like so:

import { C0NST } from './constants';

console.log(C0NST); // "constant"

但是,当我在组件模板中访问它时:

However, when I access it in a component template:

some.component.ts :

import { C0NST } from './constants';

some.component.html :

{{ C0NST }} <!-- Outputs nothing -->

但是,在组件类中定义成员的工作原理是

However defining a member in the component class works:

some.component.ts

public const constant = C0NST;

some.component.html

{{ constant }} <!-- constant -->

我不明白为什么即使我将其导入组件类中也能直接在服务类中而不是在组件模板中访问导入的常量.

I don't understand why I was able to access the imported constant directly in the service class but not in the component template even though I imported it in the component class.

推荐答案

在Angular2中,模板只能访问组件类的字段和方法.其他一切都是禁止进入的.这包括对组件类可见的东西.

In Angular2, the template can only access fields and methods of the component class. Everything else is off-limits. This includes things which are visible to the component class.

解决此问题的方法是在组件内部拥有一个仅引用常量的字段,而改用该字段.

The way to go around this is to have a field inside the component, which just references the constant, and use that instead.

这是设计的局限性,但是也许您应该更多地考虑为什么首先需要在模板中添加常量.通常,这些东西是由组件本身或服务使用的,而不是由模板使用的.

It's one limitation of the design, but perhaps you should thing more about why you need a constant in the template in the first place. Usually these things are used by components themselves, or services, but not the template.

这篇关于如何在Angular 2组件和服务中访问常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆