【问题标题】:Angular 2 - Syntax: Use of $ and { } [duplicate]Angular 2 - 语法:使用 $ 和 { } [重复]
【发布时间】:2018-03-15 11:40:02
【问题描述】:

我对 Angular 和 TypeScript 完全陌生,正在做一个教程(英雄之旅)。

出现以下行:

const url = `${this.heroesUrl}/${id}`;

它从

生成一个字符串 (?)
private heroesUrl = 'api/heroes';

以及作为参数传递给函数的 id:number。

我明白这里发生了什么,但我不明白语法。 为什么要使用 $ 以及为什么要使用方括号?

我本来希望是这样的:

const url = heroesUrl + id.toString();

【问题讨论】:

  • 或者,如果您要问为什么要使用特定语法而不是其他一些转义字符,那么这对 SO 来说并不是一个真正的问题。

标签: angular typescript


【解决方案1】:

JavaScript 中的模板字符串用记号而不是引号表示。

例如:

const variables = 'EXAMPLE';

let normal = 'A normal string allows no ${variables} ' +
    'and cannot cross lines, without the concatenation trick shown here.';

let template = `A template string does allow ${variables} 
and line breaks too.`;

在模板文字中,标记 ${variables} 将被替换为值 EXAMPLE - 也允许换行。

【讨论】:

    猜你喜欢
    • 2016-07-14
    • 2016-06-28
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2017-04-27
    • 2017-06-11
    相关资源
    最近更新 更多