2017-07-10 12 views
0

一部の文字列を外部化したいが、それでも文字列置換の形式を使用したい。文字列を外部化し、フォーマッタを使用して文字列に変数を代入する

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']; 

答えて

1

使用矢印機能:

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 
+1

どのように 'Parameter 'country'を暗黙的に回避するには、ファイルの先頭にすべてのvarsを宣言する必要はありません。 – bobbyrne01

+0

私はこの例を変更しました:' noImplicitAny'で動作します。 – ideaboxer

+0

あなたは{readonly [name:string]:(key:string)=> string} 'をとり、他のどこかの型として定義することができます。 'type ConstantsType = {読み取り専用[名前:文字列]:(キー:文字列)=>文字列}'。たとえば、ファイル内で必要な場所にインポートすることができます。次に、 'const Constants:ConstantsType = {...}'と書くことができます。 – ideaboxer

0

文字列の補間は、クラスがロードされたときに存在するためにあなたの変数countryを必要とします。後で定数文字列を書式化する場合は、通常の引用符(シングルまたはダブル)を使用して、formatをサービスで呼び出す必要があります。

関連する問題