使用Ember中的ajax从非RESTful API读取JSON数据

时间:2013-11-08 23:50:46

标签: 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
    )

基本上我试图从项目中的“项目”中获取ID以将其用于slug和ItemsItemRoute,将其推入URL以获取单个项目属性。我认为这是我出错的地方(ItemsItemRoute)。

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

2 个答案:

答案 0 :(得分:1)

如果您希望将资源与父资源分开,则应将路由器更改为以下内容:

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

但是如果你只是想抓住已经获取的模型并保持相同的外观,没有理由重新获取数据,因为你已经得到它,你应该只使用modelFor并从父资源中获取它

http://jsbin.com/eCOzOKe/1/edit

App.ItemsItemRoute = Ember.Route.extend
  model: (params) ->
    itemsModel = @modelFor("items")
    item = itemsModel.findProperty("id", params.slug)
    item

此外,您不需要使用单词slug,您只需使用:id并从模型中删除仅将id作为slug返回的计算属性

答案 1 :(得分:1)

您的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