Not able to bind data in posts.hbs - ember.js

templates/posts.hbs
<h2>Posts</h2>
{{#each model as |post|}}
<div>
<h3>{{post.postid}}</h3>
<h3>{{post.title}}</h3>
<h3>{{post.userid}}</h3>
<h4>{{post.description}}</h4>
</div>
{{/each}}
{{outlet}}
serializers/posts.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType){
payload = {data: payload};
console.log(payload); //in console getting data here properly
return this._super(store, primaryModelClass, payload, id, requestType);
}
});
routes/posts.js
import Ember from 'ember';
export default Ember.Route.extend({
model(){
let posts = this.store.findAll('post');
console.log(posts);
return posts;
}
});
Getting data from backend API point and printing data in console properly. Everything fine.
But not binding in handlebars (posts.hbs). Can someone help me with this? New to ember Js.
In routes/posts.js from console.log(posts) I'm getting one error
reason: EmberError
description: undefined
fileName: undefined
lineNumber: undefined
message: "Assertion Failed: Encountered a resource object with an undefined type (resolved resource using blog-front-end#serializer:post:)"
name: "Error"
number: undefined
stack: "Error: Assertion Failed: Encountered a resource object with an undefined type (resolved resource using blog-front-end#serializer:post:)↵ at new EmberError (http://localhost:4200/assets/vendor.js:30297:21)↵ at assert (http://localhost:4200/assets/vendor.js:17992:13)↵ at Object.assert (http://localhost:4200/assets/vendor.js:30109:34)↵ at Class._normalizeResourceHelper (http://localhost:4200/assets/vendor.js:89458:61)↵ at Class._normalizeDocumentHelper (http://localhost:4200/assets/vendor.js:89413:25)↵ at Class._normalizeResponse (http://localhost:4200/assets/vendor.js:89512:36)↵ at Class.normalizeArrayResponse (http://localhost:4200/assets/vendor.js:90051:19)↵ at Class.normalizeFindAllResponse (http://localhost:4200/assets/vendor.js:90021:42)↵ at Class.normalizeResponse (http://localhost:4200/assets/vendor.js:89997:48)↵ at Class.superWrapper (http://localhost:4200/assets/vendor.js:36019:22)"
__ember1605717703192: "ember449"

Related

record was saved to the server, but the response does not have an id and your record does not either

I’m facing this error since yesterday, Error: Assertion Failed: 'todo' was saved to the server, but the response does not have an id and your record does not either.
I know it should come from app/serializers/todo.js or my app/routes/application.jsbut after looking into severals forum, I have to ask the question to expert emberJs dev, as i’m a newbie :smiley:
Here’s my app/serializers/todo.js:
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments); // Get default serialization
json.id = record.id; // tack on the id
return json;
}
});
And my app/routes/application.js
import Route from '#ember/routing/route';
export default Route.extend({
model(){
return this.store.findAll('todo');
},
actions: {
createtodo: function() {
var titleInput = this.get("newTitle")
var todo = this.store.createRecord('todo', {
title: titleInput,
isCompleted: false
});
this.set('newTitle', '');
todo.save();
}
}
});
The way the createtodo action is triggered app/templates/application.hbs:
{{input type="text" id="new-todo" value=newTitle}}
<button {{action "createtodo"}}>Save</button>
So my objec is created but not save. When i’m looking into my ember Inspector, I see that each object I create have an ID but the title field is null or "".
This is a todoApp with an Rails-API as back and Ember as front.
Anyone see what’s wrong here ?
Your serializer is the problem. If you're using a somewhat standard api setup, you shouldn't really need the serializer at all. I'd delete that first.
What's likely happening is that your API isn't setup to recieve JSON-API documents, which are structured like:
{
id: <id>,
type: <type>,
attributes: {
name: <string>,
created: <date>,
complete: <boolean>
}
}
So you should either install a json-api gem on the backend or switch the adapter to use the DS.RestSerializer, which has a totally flat data structure.

Ember data Error: the adapter's response did not have any data

I just upgraded an app from Ember 1.13 to Ember 2.12. Now my attempts to load the data store are failing. This line:
return this.store.find('blog', 14);
generates this error: "Error while processing route: blogs.index Assertion Failed: You made a findRecord request for a blog with id 14, but the adapter's response did not have any data".
But the data is arriving, and in this format:
{
"blogs": {
"id": 14,
"person_id": "1",
"access": "3"
}
}
My adapter is specified in application/adapter.js as:
export default DS.RESTAdapter.extend({
host: "http://localhost",
namespace: 'api-rick'
});
Anyone know why I'm getting this error? I think the JSON is properly formatted -- didn't have any problems before I upgraded Ember.
Later EDIT, here's relevant code:
//application/adapter.js
import DS from 'ember-data';
import Ember from 'ember';
export default DS.RESTAdapter.extend({
host: "http://localhost",
namespace: 'api-rick',
pathForType: function(type) {
//this so types (db table names) are singular;
//else are pluralized in Adapter's request
return Ember.String.singularize(type);
}
});
//application/serializer.js
port DS from 'ember-data';
export default DS.RESTSerializer.extend({
});
//pods/contact/model.js
import DS from 'ember-data';
export default DS.Model.extend({
name : DS.attr(),
});
//pods/contact/route.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('contact');
},
});
//payload returned when viewed in Chrome's developer tools (contact table has only the one record):
{
"contact": [
{
"id": 1,
"name": "Bilbo the duck"
}
]
}
Finally, here's the errors reported in Chrome's console:
Transition #0: contact: calling beforeModel hook
ember.debug.js:55891
Transition #0: contact: calling deserialize hook
ember.debug.js:28573
Error while processing route: contact Assertion Failed: You made a `findAll` request for contact records, but the adapter's response did not have any data Error
at assert (http://localhost:4200/assets/vendor.js:20732:13)
at Object.assert (http://localhost:4200/assets/vendor.js:32400:34)
at assert (http://localhost:4200/assets/vendor.js:85626:37)
at http://localhost:4200/assets/vendor.js:97389:41
at tryCatch (http://localhost:4200/assets/vendor.js:73561:14)
at invokeCallback (http://localhost:4200/assets/vendor.js:73576:15)
at publish (http://localhost:4200/assets/vendor.js:73544:9)
at http://localhost:4200/assets/vendor.js:53448:16
at invokeWithOnError (http://localhost:4200/assets/vendor.js:15377:16)
at Queue.flush (http://localhost:4200/assets/vendor.js:15436:9)
If your backend is responding with underscore then you need to have the below code,
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.underscore(attr);
}
});

Emberjs: cannot read property 'type' of undefined

I have created a model in my ember app called ticket-stats:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
get_tickets_more: attr(),
get_tickets: attr(),
get_avg_tickets: attr()
});
The data is pulled from JSON api: http://domain.com/data/ticketStats?blah=blah...
So i have added a special adapter for this model called ticket-stats:
import JSONAPIAdapter from 'ember-data/adapters/json-api';
export default JSONAPIAdapter.extend({
host: 'http://domain.com',
namespace: 'data',
pathForType: function(type) {
return Ember.String.camelize(type);
}
});
I get the data for this model in route:
import Ember from 'ember';
export default Ember.Route.extend({
model () {
var ticketData;
this.store.query('ticket-stats', { teamID: 218, attUID: 'oc7569', useProd: 1})
.then(function(stats) { ticketData = stats; });
return Ember.RSVP.hash({
currentUser: this.currentUser,
ticketStats: ticketData
});
}
});
And, i get a TypeError:
ember.debug.js:32096 TypeError: Cannot read property 'type' of undefined
at _pushInternalModel (store.js:1524)
at push (store.js:1501)
at finders.js:171
at Object.Backburner.run (ember.debug.js:678)
at _adapterRun (store.js:1733)
at finders.js:168
at tryCatch (ember.debug.js:53806)
at invokeCallback (ember.debug.js:53821)
at publish (ember.debug.js:53789)
at ember.debug.js:32054onerrorDefault # ember.debug.js:32096exports.default.trigger # ember.debug.js:54476(anonymous function) # ember.debug.js:55727Queue.invoke # ember.debug.js:333Queue.flush # ember.debug.js:397DeferredActionQueues.flush # ember.debug.js:205Backburner.end # ember.debug.js:560(anonymous function) # ember.debug.js:1126
Any ideas as to why this is happening? This error goes away when i remove the pathForType function in the adapter, but then i get another error about getting the data from http://domain.com/data/ticket-stats?... which is not the correct URL. I have to convert to camelCase, ticket-stats => ticketStats.
This is what my json looks like:
{
"get_avg_tickets": { ... },
"get_tickets_more": { ... },
"get_tickets": { ... }
}
I also modified the application serializer by simply replacing JSONAPISerializer with JSONSerializer: app/serializers/application.js
import JSONSerializer from 'ember-data/serializers/json';
export default JSONSerializer.extend({
});
Any help would be appreciated! I'm very new to Ember.
you need to use this serializer here is the reference link
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
payload = { ticketStats: payload };
return this.normalizeArrayResponse(store, primaryModelClass, payload, id, requestType);
},
});
your json should be in this format:
{
"get_avg_tickets": 45,
"get_tickets_more": propertyvalue,
"get_tickets": propertyvalue
}
otherwise you need to normalize your response in normalizeQueryreponse of serilializer
Also ready following doc for your help
http://thejsguy.com/2015/12/05/which-ember-data-serializer-should-i-use.html
i hope it will help you. dont forget to accept my answer.
you need to use serializers which are best suited for your json data.
http://emberjs.com/api/data/classes/DS.JSONAPISerializer.html
This error is raising because your json data received from api is not fully fit into you application requirements for json formate.
Please Share json data here. because domain.com json url is not working.
there are so many issues in your code. let me to guide you one by one

setting model from route upon action received in ember.js

I am trying to set a model value from an action received by my route.
//app/routes/map.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return {
trail: null
};
},
actions: {
event: function(name, value) {
if (name === 'trail.selected') {
this.modelFor('map').set('trail', value);
}
}
}
});
when I try to use
this.modelFor('map').set('trail', value);
I get the following error:
Uncaught TypeError: this.modelFor(...).set is not a function
When I try to use
this.modelFor('map').trail = value;
I get that error
Uncaught Error: Assertion Failed: You must use Ember.set() to set the trail property (of [object Object]) to <nested-component#model:mtg-trail::ember617:kvdpo>.
EDIT Added template
//app/templates/map.hbs
<h2>Trail's name: {{trail.name}}</h2>
{{#if trail}}
{{map-draw trail=trail.id}}
{{/if}}
Your routes model isn't an ember object so set won't work. Try:
model: function() {
return Ember.Object.create({
trail: null
});
},
Also, changing the models content from an action should really be done on the controller.
Well, since the action you are calling is on the 'map' route itself, why not just:
this.set('model.trail', value);

How do I display Promise rejection data in Ember's error template?

I want to display information about the rejected model promise in my Ember error templates. The Ember error routing documentation says:
The "reason" for the error (i.e. the exception thrown or the promise reject value) will be passed to that error state as its model.
So here is some code trying to test this, with an application route that rejects a promise with an error message, and an error route and template that tries to display it:
App.Router.map(function() {
this.route('fail');
});
App.FailRoute = Ember.Route.extend({
model: function() {
return new Ember.RSVP.Promise(function(resolve, reject) {
reject('This is an error message');
});
}
});
App.ErrorRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super.apply(this, arguments);
// This always alerts with "Error model is null", when I expect
// "Error model is This is an error message" instead
alert('Error model is ' + model);
}
})
And the error template:
<h2>An error happened</h2>
{{#if model}}
Message: {{model}}
{{else}}
But no message was given
{{/if}}
When I try to do this, my error route (and therefore template) never receives the rejection object as its model.
Here is a JSBin with the above code.
This appears to be a bug, but at least in the case of rejection through a promise - here is what worked for me.
App.FailRoute = Ember.Route.extend({
model: function() {
return new Ember.RSVP.Promise(function(resolve, reject) {
reject('This is an error message');
});
},
actions: {
error: function(error, transition) {
this.transitionTo('error', error);
return true;
}
}
});
Then, in the error template:
<script type="text/x-handlebars" data-template-name="error">
{{link-to 'Back' 'index'}}
<h2>An error happened</h2>
{{#if model}}
Message: {{model.error}}
{{else}}
But no message was given
{{/if}}
</script>
Your updated (working) JSBIN here
This is kind of annoying, but the reason you pass to reject has to be an object for it to be properly passed to the error state as its model.
Here's all you need:
App.FailRoute = Ember.Route.extend({
model() {
return new Ember.RSVP.Promise((_, reject) => {
reject({error: 'This is an error message'});
});
}
});
And then for your error template you just reference {{model.error}}.
That worked for me, whereas just using a string as the reason didn't...