javascript - 在 Ember 中使用 ajax 从非 RESTful API 读取 JSON 数据

标签 javascript ember.js coffeescript ember-data

我正在为一个学习项目构建一个小型黑客新闻阅读器,其中我正在阅读的 API 有点不标准(因此 ember-data 是不可能的,除非有人知道如何硬塞它)。

项目列表在这里:http://node-hnapi.herokuapp.com/news而单个项目是这样的:http://node-hnapi.herokuapp.com/item/6696691

这是我到目前为止所做的事情:http://jsbin.com/OFeCoR/22/edit?html,js,output

App = Ember.Application.create()

baseURL = "http://node-hnapi.herokuapp.com"
newsURL = "/news"
itemURL = "/item/"

App.Items = Ember.Object.extend(  
  id: ""
  title: ""
  url: ""
  points: ""
  user: ""
  time_ago: ""
  comments_count: ""
  slug: (->
    @get("id")
  ).property("id")
)

App.Items.reopenClass 
  all: ->
    Ember.$.getJSON(baseURL + newsURL).then (response) ->
      items = []
      response.forEach (n) ->
        items.push App.Items.create(n)
      items     

App.Router.map ->
  @resource "items", ->
    @route "item",
      path: ":slug"

App.IndexRoute = Ember.Route.extend
  beforeModel: ->
    @transitionTo "items"

App.ItemsRoute = Ember.Route.extend
  model: ->
    App.Items.all()

App.ItemsItemRoute - Ember.Route.extend
  model: (params) ->
    itemID = App.Items.findProperty("id", params.id)
    Ember.$.getJSON((baseURL + itemURL + itemID).then (response) ->
      item = []
      response.forEach (i) ->
        item.push App.Item.create(i)
      item
    )

基本上,我试图从 items 中的“item”获取 ID,以将其用于 slug,并在 ItemsItemRoute 中将其插入 URL 以获取各个 item 属性。我认为这是我出错的地方(ItemsItemRoute)。

我认为仅在单击链接/操作时获取单个项目数据而不是从一开始就获取所有项目数据可能是有意义的。关于如何解决这个问题有什么想法吗?

最佳答案

您的App.ItemsItemRoute有一些错误:

# you are using minus (-) this is a assigment and a equals (=) is needed
App.ItemsItemRoute - Ember.Route.extend
  model: (params) ->
    # App.Items.findProperty don't exist and params.id isn't present just params.slug because you mapped your route with path: ":slug"
    itemID = App.Items.findProperty("id", params.id)
    Ember.$.getJSON((baseURL + itemURL + itemID).then (response) ->          
      item = []
      # this will return just one item, no forEach needed
      response.forEach (i) ->
        item.push App.Item.create(i)
      item
    )

我更新了以下内容:

App.ItemsItemRoute = Ember.Route.extend
  model: (params) ->    
    Ember.$.getJSON(baseURL + itemURL + params.slug).then (response) ->
      App.Items.create(response)

并在每个项目中添加了一个 {{link-to}} 以便能够转换到 ItemsItemRoute

这是更新后的 jsbin http://jsbin.com/OlUvON/1/edit

关于javascript - 在 Ember 中使用 ajax 从非 RESTful API 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19870563/

相关文章:

javascript - sinon spy 不在具有异步功能的 stub 中调用

javascript - ngStyle AngularJs 放置变量属性

ember.js - 接受服务器更新时保存记录

javascript - 如何将主干模型插入子集合?

javascript - POST 请求中的测试和 stub 参数

javascript - 自动复制和粘贴 - Ajax/JS

javascript - Ember,如何为 "partial"和 "index"重用相同的 "show"

javascript - Ember 2,使用 ember-truth-helpers 等插件进行表演,而不仅仅是 Ember 默认方式

javascript - 创建空字符串数组?

javascript - 主干 View 未定义