我已经从我的代码中提取了所有字符串,并将它们放入一个名为constants.ts
的文件中。
export class Constants {
public static API_URL = '/api/';
public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create-child';
}
我能够使用 console.log
将值替换为字符串:
import { Constants } from '../common/constants';
console.log(Constants.CREATE_CHILD_API_URL, 'dummyId');
在控制台中生成此内容:/api/dummyId/create-child
这是目标。
我怎样才能做同样的事情,但将结果存储在变量中以供以后使用?
我可以使用本机并在现代浏览器上运行而无需拉入库的东西吗?
Template literals
似乎不适合用例,因为变量不会在我的常量文件中定义。
这种方法最终会出错。我宁愿建议使用具有某些参数的函数,这些函数将通过在内部执行字符串插值来生成您需要的字符串:
export class Urls {
public static API_URL = '/api/';
public static CREATE_CHILD_API_URL =
(id: string) => `${Urls.API_URL}${id}/create-child`;
}
稍后您将能够像这样使用它:
import { Urls } from '../common/urls';
const forLaterUse = Urls.CREATE_CHILD_API_URL('dummyId');
console.log(forLaterUse);