我正在尝试编写小型搜索应用程序,但我很沮丧地根据某些操作更新模型。
适配器/ application.js中
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'http://c6403:2222',
namespace: 'server'
});
串行器/ results.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizePayload: function(payload) {
return {
title: payload.title,
description: payload.description,
type: payload.type,
url: payload.url,
};
}
});
模型/ results.js:
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
url: DS.attr('string'),
type: DS.attr('string'),
searchText: DS.attr('string')
});
模板/ index.js
{{search-home action="submitsearch"}}
{{search-list searchlist=model}}
模板/组件/搜索list.hbs
{{#each searchlist as | searchItem|}}
<li>{{searchItem.title}}</li>
<li>{{searchItem.description}}</li>
<li>{{searchItem.url}}</li>
{{/each}}
路线/ index.js:
import Ember from 'ember';
export default Ember.Route.extend({
model: function (params){
return [
{
title: 'Rails is Omakase1',
description: 'Lorem ipsum',
url: 'google.com',
type: 'sf'
},
{
title: 'Rails is Omakase2',
description: 'Lorem ipsum',
url: 'google.com',
type: 'sf'
}
]
},
actions:{
submitsearch: function(searchText) {
this.get('store').query('results', { searchText });
this.refresh();
}
}
搜索list.hbs:
<ul>
{{#each searchlist as | searchItem|}}
<li>{{searchItem.title}}</li>
<li>{{searchItem.description}}</li>
<li>{{searchItem.url}}</li>
{{/each}}
我的JSON回复
[
{
"url":"https://login.salesforce.com/",
"title":"This is SF KB",
"description":"This is SF HCC",
"type":"SF"
},
{
"url":"https://issues.apache.org/jira/secure/Dashboard.jspa",
"title":"This is SF JIRA",
"description":"This is SF HCC",
"type":"JIRA"
}
]
当我提交我的搜索时 - 我可以看到它正在调用JSON调用并从服务器中提取数据。但我发现错误为&#34; 断言失败:对store.query的响应应该是一个数组,但它只是一个记录。请将您的回复包装在一个数组中,或使用store.queryRecord
查询单个记录。
错误 &#34;
你能指点我在这做什么错误吗?
答案 0 :(得分:0)
让ember-data为您带来魔力:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
submitSearch(searchText) {
this.get('store').query('index', { searchText });
}
},
model() {
/*
* Retrieve all available record in store for model.
* If you allready have search criteria (e.g. from query params)
* you might want to use `query` method of ember-data.
* If you don't want to make a call to server before user
* enters search criteria just use stores `peekAll` method.
* By the way "index" is a very confusing name for a model.
*/
return this.get('store').findAll('index');
}
});
您的路线模型是商店中可用的所有索引记录。如果您通过调用this.get('store').query()
或类似方法从商店检索新记录,则会将其推送到商店并由模型检索。
请注意,您可能必须为api端点编写适配器和序列化程序。
更新:感觉像是一个新问题,但作为一个简短提示:没有normalizePayload
hook im ember-data 2.x.它在1.13中弃用,在2.x中删除。我想你正在寻找normalizeRecord
。