Ember.js 从 url 获取 JSON 数据

Y. *_* C. 1 ember.js

我有一点困惑。组件、控制器、路由、助手等等。我只是想从 JSON 文件中获取一个值并使用 Ember.Helper 上的值进行计算。我应该使用哪种方式,我不知道了,大脑烧伤了。有人可以帮我获取“market_name”中等于“ https://stocks.exchange/api2/prices ”上的“BTC_USDT”的“卖出”部分并将其放入助手中吗?

编辑:

事实上我尝试做类似的事情。

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);
Run Code Online (Sandbox Code Playgroud)

从index.hbs

{{format-btc 0.001}}
Run Code Online (Sandbox Code Playgroud)

还是没能找到合适的解决办法。我得到 data[i].sell 作为 btc_price,但无法将其传递到返回部分...我缺少什么?或者我做错了什么?

Tre*_*ama 5

您遇到的问题是因为 ajax 请求执行。函数继续执行并返回 Promise 返回之前的值。

虽然从技术上讲,您可以修复此问题并在辅助函数中使用 async/await,但您会遇到另一个问题 - 每次调用辅助函数时,您都会发出一个新的 ajax 请求,该请求将获取当前价格并计算值。

我的建议是,不要使用助手,而是使用模型和控制器的组合。因为您目前对框架感到不知所措,所以我实际上会提出使用服务+组件的第二个建议

我推荐一项服务或模型,因为您希望保留从定价源获取的数据。如果不这样做,助手/组件的每个实例都会发出新的请求来获取数据。

服务

服务是 ember 中的一种会话集合。它仅被实例化一次,之后数据将持续存在。

ember g service pricing

在 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);
    })
}
Run Code Online (Sandbox Code Playgroud)

成分

然后,您可以将服务注入到组件中并使用一致的价格。

ember g component format-btc
Run Code Online (Sandbox Code Playgroud)

修改组件的控制器以注入服务并计算新值。

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

该组件的模板将简单地返回转换后的价格。

#templates/components/format-btc.js
{{convertedPrice}}
Run Code Online (Sandbox Code Playgroud)

您将调用该组件,并传入比特币作为参数

{{format-btc bitcoints='1234'}}
Run Code Online (Sandbox Code Playgroud)

所有这些都是伪代码,并且可能不起作用。但是,您仍然应该能够接受指导并将信息组合在一起以获得您想要的结果。