相关疑难解决方法(0)

如何访问Angular 2组件和服务中的常量?

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

export const C0NST = "constant";
Run Code Online (Sandbox Code Playgroud)

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

import { C0NST } from './constants';

console.log(C0NST); // "constant"
Run Code Online (Sandbox Code Playgroud)

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

some.component.ts:

import { C0NST } from './constants';
Run Code Online (Sandbox Code Playgroud)

some.component.html:

{{ C0NST }} <!-- Outputs nothing -->
Run Code Online (Sandbox Code Playgroud)

但是,在组件类中定义成员有效:

some.component.ts

public const constant = C0NST;
Run Code Online (Sandbox Code Playgroud)

some.component.html

{{ constant }} <!-- constant -->
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我能够直接在服务类中访问导入的常量,但不能在组件模板中访问,即使我在组件类中导入它.

typescript angular

49
推荐指数
5
解决办法
6万
查看次数

Typescript错误,因为类型没有重叠,所以此条件将始终返回“ true”

我在表单组上有此条件:

if((age>17 && (this.frType=="Infant")) 
|| (age>40 && this.frType=="Grandchild")
|| (age<=5 && 
   (this.frType!="Child" 
   || this.frType!="Infant" 
   || this.frType!="Grandchild" || this.frType!="Cousin")))
Run Code Online (Sandbox Code Playgroud)

它包含3个主要条件:

  1. 如果年龄17岁,则无法设置为 infant
  2. 如果一个人大于40岁,他就不能成为 grandchild
  3. 如果一个人是不到5年时间,他应该是childinfantgrandchildcousin

如果这些条件之一为真,我将发送一条错误消息。

我收到的错误是:

[ts]由于类型'“ Child”'和'“ Infant”'没有重叠,因此此条件将始终返回'true'。[2367]

在这部分if条件上:

|| this.frType!="Infant" || this.frType!="Grandchild" || this.frType!="Cousin")))
Run Code Online (Sandbox Code Playgroud)

我在其他组件中使用了确切的条件,并且没有显示错误。

if((age>17 && (this.family_relation_type=="Infant")) 
|| (age>40 && this.family_relation_type=="Grandchild")
|| (age<=5 && 
   (this.family_relation_type!="Child" || 
    this.family_relation_type!="Infant" || 
    this.family_relation_type!="Grandchild" || 
    this.family_relation_type!="Cousin")))
Run Code Online (Sandbox Code Playgroud)

这是我在这两个部分中计算年龄的方式:

let timeDiff = Math.abs(Date.now() - this.formGroup.controls['dob'].value);
let age = Math.floor((timeDiff / (1000 * 3600 * …
Run Code Online (Sandbox Code Playgroud)

javascript typescript typescript2.0 angular

8
推荐指数
4
解决办法
1万
查看次数

标签 统计

angular ×2

typescript ×2

javascript ×1

typescript2.0 ×1