我想外部化一些字符串,但仍然使用某种形式的字符串替换。
在我使用过的一些基于node
的项目中:
var format = require('string-format');
format(Constants.COUNTRY_WEATHER_ENDPOINT, {
country: country
})
但是在Typescript
,我一直在尝试这样的事情..
错误:
Cannot find name 'country'.at line 18 col 66 in repo/src/app/constants.ts
Constants.ts
export class Constants {
public static COUNTRY_WEATHER_ENDPOINT = `/api/country/${country}/weather`;
}
TestService.ts
import { Constants } from './constants';
export class TestService {
constructor(private $http) { }
public getWeather(country) {
let url = Constants.COUNTRY_WEATHER_ENDPOINT;
return this.$http.get(
url,
.then(response => response);
}
}
TestService.$inject = ['$http'];
使用箭头函数:
export const Constants: { readonly [name: string]: (key: string) => string } = {
countryWeatherEndpoint: country => `/api/country/${country}/weather`
}
然后做:
import { Constants } from "./constants";
// ...
const url = Constants.countryWeatherEndpoint(country);
// use your url
Typescript 中的字符串插值需要在加载类时存在变量country
。如果要稍后格式化常量字符串,则必须使用普通引号(单引号或双引号(并在服务中调用format
。