【发布时间】:2017-07-05 12:43:52
【问题描述】:
我需要插入一个字符串变量,但这不起作用。 有没有办法插入这个变量?直接做替换更好吗?
例如:
time = duration.years();
dateTime = this.i18nService.getTranslation('past-date-years');
//dateTime value is = "${time} years ago"
console.log(`${dateTime}`); //not working
console.log(`${time} years ago`);//working
【问题讨论】:
-
定义“不工作”。第一个
console.log()调用实际上得到了什么输出?顺便说一句,标题中问题的答案是“是”。 -
您确定
dateTime变量中有内容吗?尝试调试或只是console.log(dateTime) -
是的,我确定。控制台.log(
${dateTime}); = "${time} years ago" console.log(${time} years ago); = "3 年前" -
这是一个老问题,但我认为罗伯托想问的是“你能以编程方式解析可能包含模板的变量吗?”。通过使用反引号,编译器将硬编码的字符串视为模板,但这仅适用于硬编码的字符串。他需要的是一个 function 来解析给定的字符串,我认为 Typescript 中不存在该字符串(至少直到 2018 年 12 月我写这篇文章时)。这样的函数也必须谨慎使用,因为它会允许代码注入。