VIK*_*HLI 3 javascript interpolation typescript template-strings angular
变量文件:
export class VariableSettings {
public static string_value: string = 'vikas/${id}/data';
}
Run Code Online (Sandbox Code Playgroud)
其他文件.
import {VariableSettings} from './variables';
getData(id:string ){
console.log(`${VariableSettings.string_value}`, `${id}`);
// it prints vikas/${id}/data abcd11123
}`
Run Code Online (Sandbox Code Playgroud)
现在我希望结果像"vikas/abcd11123/data".那么如何在该字符串中注入id.
任何有关相同的建议将不胜感激.
谢谢
要使用插值字符串,您需要``像在第二个代码段中一样使用字符串分隔符.如果您已经使用非插值字符串来保存设置的值,则无法使用插值功能对其进行插值(您可以使用正则表达式执行替换,但这有点混乱).
最简单的解决方案是使字段成为一个函数并id作为参数
export class VariableSettings {
public static USER_BOOKINGS = (id: number) => `vikas/${id}/data`;
}
console.log(`${VariableSettings.USER_BOOKINGS(10)}`);
console.log(VariableSettings.USER_BOOKINGS(10)); // Or no interpolation at call site, not needed anymore if you just need the single value
Run Code Online (Sandbox Code Playgroud)
现在USER_BOOKINGS将是一个函数,它将构造字符串所需的参数作为参数.这样,字符串所需的参数是清晰且类型安全的.
| 归档时间: |
|
| 查看次数: |
906 次 |
| 最近记录: |