Menahem Gil
Menahem Gil

Reputation: 829

variable inside a string in Angular / typescript

I have a service that I get an http from API

export class DataDisplayFromAPI {

result:any;

constructor(private _http: HttpClient) {}

getPrices() {
    return this._http.get("https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,LTC,BCH,IOT,XRP&tsyms=USD")
    .map(result => this.result = result);
}
}

What I try to do is to replace the coins list BTC,ETH,LTC,BCH,IOT,XRP inside the string with a variable, as follow:

export class DataDisplayFromAPI {

result:any;
coinsList = 'BTC,ETH,LTC,BCH,IOT,XRP';

constructor(private _http: HttpClient) {}

getPrices() {
    return this._http.get("https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + coinsList + "&tsyms=USD")
    .map(result => this.result = result);
}
}

But get error.

I tried also

return this._http.get(`https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinsList}&tsyms=USD`)

But it also doesn't work

How can I do it?

Thanks

Upvotes: 0

Views: 3175

Answers (1)

LLai
LLai

Reputation: 13396

coinsList is not defined in the method's scope. You need to refer to the component's scope with this

getPrices() {
    return this._http.get("https://min-api.cryptocompare.com/data/pricemulti?fsyms="
    + this.coinsList +
    "&tsyms=USD")
    .map(result => this.result = result);
}

or

getPrices() {
    return this._http.get(`https://min-api.cryptocompare.com/data/pricemulti?fsyms=${this.coinsList}&tsyms=USD`)
        .map(result => this.result = result);
}

Upvotes: 3

Related Questions