简体   繁体   English

Ember.js从URL获取JSON数据

[英]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. 我只是想从JSON文件中获取一个值,然后使用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? 有人可以帮我获取“ https://stocks.exchange/api2/prices ”上等于“ BTC_USDT”的“ market_name”的“卖出”部分并将其放入帮助器中吗?

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 并从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? 我以btc_price的形式获取数据[i] .sell,但无法将其传递回来以返回零件...我缺少什么? or what am i doing wrong? 还是我做错了什么?

The issue you're encountering is because the ajax request executes. 您遇到的问题是因为执行了ajax请求。 Execution of the function continues and returns the value before the promise returns. 继续执行函数,并在promise返回之前返回值。

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. 从技术上讲,您可以解决此问题并在helper函数中使用async / await,但会遇到另一个问题-每次调用helper时,您都会发出一个新的ajax请求,该请求将获取当前价格并计算价值。

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. 服务是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. 在init块中,设置默认值并发出ajax请求。

# 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. 但是,您仍然应该能够获得指导并将信息拼凑起来以获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM