【问题标题】:How to pull data from an outside API using EmberJS?如何使用 EmberJS 从外部 API 中提取数据?
【发布时间】:2017-02-04 10:37:10
【问题描述】:

所以我正在努力学习 EmberJS,我正在努力学习这个。基本上,我有以下基本结构

模板:

<ul>
  {{#each model as |game|}}
    <li>{{game.title}} - {{game.console}}</li>
  {{/each}}
</ul>

路由文件:

export default Ember.Route.extend({
    model() {
        return [
         {'title':'Super Mario Bros', 'console':'NES'},
         {'title':'Pac Man', 'console':'Arcade'},
         {'title':'Galaga', 'console':'Arcade'},
         {'title':'Frogger', 'console':'Arcade'},
         {'title':'Marvel vs. Capcom', 'console':'Arcade'},
         {'title':'The Legend of Zelda', 'console':'NES'},
         {'title':'CastleVania', 'console':'NES'},
         {'title':'Final Fantasy IV', 'console':'SNES'}];
    }
});

但是,我想使用 GET 调用从 Apiary API 链接中提取它,而不是像我在这里那样硬编码它。我该怎么做?

(养蜂场https://private-9c66cc-managementconsole.apiary-mock.com/getactiveroms

【问题讨论】:

    标签: ajax api http ember.js get


    【解决方案1】:

    对于符合 JSON 的 API,您可以执行以下操作:

    export default Ember.Route.extend({
      model() {
        let url = 'https://private-9c66cc-managementconsole.apiary-mock.com/getactiveroms';
        return Ember.$.getJSON(url);
      },
    });
    

    但是,由于此 API 不使用有效的 JSON 进行响应,因此您需要以文本形式获取 API 并在将响应解析为 JSON 之前对其进行操作。

    export default Ember.Route.extend({
      model() {
        let url = 'https://private-9c66cc-managementconsole.apiary-mock.com/getactiveroms';
        return Ember.$.ajax({
          url: url,
          dataType: 'text',
        })
        .then((result) => { 
          result = result.replace(/[ \n]+/g, '');
          result = result.substring(1, result.length - 1);
          result = result.replace(/'/g, '"');
          return JSON.parse(result);
        }, (err) => {
          console.log('err', err); 
        });
      },
    });
    

    我建议更新 API 响应以包含有效的 JSON,以便在使用时更轻松。

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 2017-12-06
      • 2017-07-06
      • 1970-01-01
      相关资源
      最近更新 更多