Y. C.
Y. C.

Reputation: 15

Ember.js getJSON data from an url

I am a bit confused. Components, controllers, routes, helpers and whatsoever. I simply want to grab a value from a JSON file and calculate it with a value on Ember.Helper. Which way should i use, i cannot know anymore, brain burned. Would someone please help me to grab the "sell" part of the "market_name" which equals to "BTC_USDT" on "https://stocks.exchange/api2/prices" and put that into helper?

Edited:

In fact i try to do something like that.

import Ember from 'ember';

export function formatBTC(value) {
    var url = 'https://stocks.exchange/api2/prices';
    var btc_price = Ember.$.getJSON(url).then(function(data) {
        for (var i=0; i <= data.length-1; i += 1)
        {
            if (data[i].market_name == "BTC_USDT")
            {
                return data[i].sell;
                console.log(data[i].sell+' - i got the value properly');
            }
        }
    });
    console.log(btc_price+' - shows nothing, i cannot pass the var btc_price to here, why not');
    calculation = value * btc_price; //some syntax may apply, maybe Number(value) or whatsoever, but i cannot have my variable btc_price returns here.
    return calculation.toFixed(8);
}

export default Ember.Helper.helper(formatBTC);

And from the index.hbs

{{format-btc 0.001}}

Still couldnt find a proper solution. I get the data[i].sell as btc_price, but couldnt pass it through to return part... what am i missing? or what am i doing wrong?

Upvotes: 1

Views: 469

Answers (1)

Trenton Trama
Trenton Trama

Reputation: 4930

The issue you're encountering is because the ajax request executes. Execution of the function continues and returns the value before the promise returns.

While technically, you could fix this and use async/await in your helper function, you'll run into another issue - Every time your helper is called, you'll make a new ajax request that will fetch the current price and calulate the value.

My recommendation is that instead of a helper, you use a combination of a model and a controller. Because you're currently overwhelmed with the framework, I'll actually make a second suggestion of using a service + component

I recommend a service or a model because you want to persist the data that you've fetched from the pricing source. If you don't, every instance of the helper/component will make a new request to fetch data.

Service

A service is kind of a session collection in ember. It only gets instantiated once, after that data will persist.

ember g service pricing

In the init block, set your default values and make your ajax request.

# services/pricing.js
btcPrice:null,
init() {
    this._super(...arguments);
    Ember.$.getJSON(...).then(val=>{
        # get correct value from response
        # The way you were getting the value in your example was incorrect - you're dealing with an array.
        # filter through the array and get the correct value first
        this.set('btcPrice',val.btcPrice);
    })
}

Component

You can then inject the service into the component and use a consistent price.

ember g component format-btc

Modify the controller for the component to inject the service and calculate the new value.

#components/format-btc.js
pricing: Ember.inject.service('pricing')
convertedPrice: Ember.computed('pricing',function(){
    return pricing.btcPrice*this.get('bitcoins')
})

The template for the component will simple return the converted price.

#templates/components/format-btc.js
{{convertedPrice}}

And you'll call the component, passing in bitcoins as an argument

{{format-btc bitcoints='1234'}}

All of this is pseudo-code, and is probably not functional. However, you should still be able to take the guidance and piece the information together to get the results you want.

Upvotes: 5

Related Questions