我正在用ajax提取一些JSON(因为我对RESTAdapter的理解有限/缺乏有用的示例/无法通过CORS…)-我正在获得这些嵌套对象。我需要一个"book"数组,但我不确定如何格式化这个JSON,使其可读。
路线/书籍.js
import Ember from 'ember';
import ajax from 'ic-ajax';
var libraryThingApi = "http://www.librarything.com/api_getdata.php?";
export default Ember.Route.extend({
model: function() {
var libraryData = ajax({
url: libraryThingApi + "userid=F.L.O.W.",
type: 'GET',
dataType: 'jsonp'
});
console.log(libraryData);
return libraryData;
}
});
退回了什么
Promise
_id: 47
_label: "ic-ajax: unwrap raw ajax response"
...
_result: Object
books: Object
111333266: Object
title: "a book title"
111730480: Object
title: "a book title"
settings: Object
theuser: "F.L.O.W."
more_things: "etc"
{
books: {
111601539: {
book_id: "111601539",
title: "Rosie Revere, Engineer",
author_fl: "Andrea Beaty",
copies: 1
},
121604536: {
book_id: "121604536",
title: "Ember for people who aren't core.",
author_fl: "No author",
copies: "This book does not exist"
}
},
settings: {
theuser: "sheriffderek"
}
}
由于您只是获取原始json,因此可以随心所欲地使用它。然后就变成了你想如何访问路线模板中的数据的问题。
Ember的模型挂钩是有promise意识的,所以您只需返回promise是正确的。该承诺的实现价值就是您对模板感兴趣的内容。因此,如果实现的值是这样的:
{
books: [
{id: 1, title: "some title", nested_data: {author: "some author"}},
{id: 2, title: "another title", nested_data: {author: "another author"}},
]
}
然后,在路由的模板中,您可以访问模型挂钩中返回的promise中的已实现值。Ember1.10之前(稍后在1.x系列中弃用),您可以在路线模板中浏览您的书籍,如下所示:
<ul>
{{#each book in model.books}}
<li>{{book.title}} by {{book.nested_data.author}}</li>
{{/each}}
</ul>
Ember 1.10及更高版本为每个语句引入了块参数:
<ul>
{{#each model.books as |book|}}
<li>{{book.title}} by {{book.nested_data.author}}</li>
{{/each}}
</ul>
点击此处阅读有关Ember1.10发布的信息。