So basically i’m trying to call an ajax request on a page for when that page loads.
I can only get this code to work if async: false is there…
<template>
<div class="page" data-name="iteminfo">
<div class="page-content">
{{Item._id}} --- {{Item.name}}
</div>
</div>
</template>
<script>
return {
data: function () {
var $ = this.$;
var app = this.$app;
app.preloader.show();
var itemId = this.$route.params.id;
var item;
app.request({
url: myApi+ 'item?itemid=' + itemId,
method: 'GET',
async:false,
dataType: 'json',
crossDomain: true,
success: function(data, textStatus ){
app.preloader.hide();
item = data[0];
},
error: function(xhr, textStatus, errorThrown){
console.log("error" + xhr);
},
});
return {
Item: item
};
}
};
</script>
if i remove the async: false, i get errors when trying to retrieve information in the using handlebars as such…{{Item._ID}} — {{Item.name}} I get TypeError: Cannot read property ‘_id’ of undefined
Is there a better way to accomplish this?
I dont know if it is a better way or not, but i use routes.js to handle this kind of data.
in routes.js
{
path: '/page/slug/:slug/',
async: function (routeTo, routeFrom, resolve, reject) {
app.preloader.show();
app.request.json('https://apiurl',{ slug:routeTo.params.slug, }, function (data) {
//console.log(data);
app.preloader.hide();
resolve(
{ componentUrl: './pages/apipage.html' },
{ context:
{
myvar: 'any static variable can be defined here...',
result: data
} }
);
})
},
}
in your template you can use data as usual {{data.someproperty}}
well first, thanks for your reply! i appreciate you taking the time to help me figure this out.
I never thought to try it like this, not sure if its better or worse or whats best practice, but i’ll be sure to experiment with it.
thank you again!
I tried the following in routes.js and it’s working also…
{
path: '/item/:id/',
async: function (routeTo, routeFrom, resolve, reject) {
app.preloader.show();
var item;
app.request({
url: myApi + 'item?itemid=' + routeTo.params.id,
method: 'GET',
dataType: 'json',
crossDomain: true,
success: function(data, textStatus ){
item = data[0];
app.preloader.hide();
resolve(
{ componentUrl: './pages/iteminfo.html' },
{ context:
{
Item: item
}
}
);
},
error: function(xhr, textStatus, errorThrown){
console.log("error" + xhr);
},
});
}
},
thank you for your help, i think i like this better than the way i was doing it, if there’s a better way i’d like to know what’s best practice