In my website I have a series of images that serve as nuxt links to game pages:
<template>
<NuxtLink :to="game.pageName">
<img :src="game.boxImage" :height="gamePanelHeight" class="elevation-4"
/></NuxtLink>
</template>
Each of those links draws its properties from a content markup file like this:
index: 3
boxImage: gameImages/box_image.png
title: game title
pageName: games/whatever
And they're loaded into the page like so:
<script>
export default {
async asyncData({ $content, params }) {
const games = await $content('games').sortBy('index', 'asc').fetch()
return { games }
},
}
</script>
Whenever I refresh this page. All of these images break until I navigate outside the page and come back. What's causing this issue and how do I fix it?
This is a static Nuxt application FYI. And it's being served through an AWS S3 bucket but I don't think that's what's causing this issue.
EDIT: Also the boxImage that's in gameImages/box_image.png is from the static folder.
asyncData is not a hook that is triggered upon reaching an URL or using a reload (F5), it is only triggered during navigation.
If you want it to work even after a reload, use the fetch() hook.
More info here: https://nuxtjs.org/docs/2.x/components-glossary/pages-fetch#options
Edit on how to write it with fetch()
<script>
export default {
data() {
return {
games: [],
}
},
async fetch() {
this.games = await this.$content('games').sortBy('index', 'asc').fetch()
},
}
</script>
Related
I'm trying to apply Google Maps API (v3) on my site, which is deployed on Heroku.
The map is populated with a given GPX file, provided by JS/Ajax.
The GPX file is stored on AmazonS3.
( I don't think that it's matter, but note the the site is built with Django, and the GPX file is a FileField of the relevant model ).
It works very well locally (local ip), but the map is not loaded at the deployed site.
I couldn't track any related error on the server logs, e.g. wrong key, etc.
Following is the relevant code snippet:
<div id="map" style="width: 50%; height: 50%;"></div>
<script>
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addRoutepointsToMap(); // Add the routepoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
function initMap() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
loadGPXFileIntoGoogleMap(map, "{{ object.gpx_file.url }}");
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=...&callback=initMap"
async defer></script>
Here is the corresponding snapshots:
Following is the console log (Chrome), while on the deployed site:
Can you please assist me with that?
Is that a GoogleMaps API issue? an AmazonS3 issue? Other?
How can I make GoogleMaps work on the deployed site?
Thanks ahead,
Shahar
I have a PWA built with ionic deep linker. I have done a demo here https://stackblitz.com/edit/ionic-mee2ut?file=app%2Fcustomer%2Fcustomer.component.html where the browser back button doesn't work as expected.
Steps to reproduce
1.In Dashboard page click on edit button.It will navigate to customer
page(see URL.It is changed to /Customer/CustomerId).
2.In Customer page, you will see the customer info and other customers
list, there click edit from other customers list.This will open another
page.(see URL.It is changed to /Customer/CustomerId).
3.Click on browser back button u can see that the URL is changed but the
view is not updated.
If I repeat steps 1 & 2 then click on nav back button instead of browser button then it works correctly.Both the URL and the view gets updated.
Is there something I am doing wrong because the browser back button does not work as expected or this is issue of ionic framework.
This is how i navigate between views
EditCustomer(Customer: any) {
this.navCtrl.push('Customer', { Id: Customer.Id, Name: Customer.Name });
}
Can somebody please tell me a way how to resolve this issue?
I saw your code in the above url, you are passing id as param but not the name so, that is the reason url is changing but data is not reflected i modified your code in app.module.ts file please replace this code in your app.module.ts file
IonicModule.forRoot(MyApp, {}, {
links: [
{ component: DashboardComponent, name: 'Dashboard', segment: 'Dashboard' },
{ component: CustomerComponent, name: 'Customer', segment: 'Customer/:Id/:Name' }
]
})
Please replace your app.module.ts with the following code
import { Component } from '#angular/core';
import { Platform, IonicApp, App } from 'ionic-angular';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = 'Dashboard';
constructor(private _app: App, platform: Platform, private _ionicApp: IonicApp,) {
platform.ready().then(() => {
this.setupBackButtonBehavior();
});
}
private setupBackButtonBehavior () {
// If on web version (browser)
if (window.location.protocol !== "file:") {
// Register browser back button action(s)
window.onpopstate = (evt) => {
//Navigate back
if (this._app.getRootNav().canGoBack())
this._app.getRootNav().pop();
};
}
}
}
I was able to use something like this:
let randomID = this.makeId(5); // random string id
this.navCtrl.push('path', {
eventID: eventID,
instituteID: instituteID,
randomID: randomID
}, {
id: `path/${eventID}/${instituteID}/${randomID}`
});
This "id" seems to fix it, but if you can go to the same page, then it requires a "random" value to separate each visit to that page.
#IonicPage({
name: 'path',
segment: 'path/:instituteID/:eventID/:randomID'
})
It looks like, by default, it uses the name of the page as an id for that view. If multiple views have same id => issue when using browser back/forward. That's where the random comes in, to separate multiple instances of the same page.
I have an application made with Ionic 2, The work flow is like this
Case A . When user is using app for the first time
User Logs in (loading is shown)
When successfully logged in loading window is hidden and user is forwarded to Dashboard page.
In dashboard page items are loaded via ajax request.
Case B. When user is already logged in before
The first screen is Dashboard and items are loaded via ajax request.
Problem
In case A, when user logs in and forwarded to DashboardPage, the loading screen doesn't gets dismissed. Sometimes it gets dismissed but most of the time it doesnot? Is this an ionic bug or am I doing something wrong??
Here is my DashboardPage
//imports here
export class DashboardPage {
public loadingmsg: any;
public ajaxRequest: any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private webservice: WebService,
private loadingCtrl: LoadingController
)
{
this.loadDashboardContents();
}
loadDashboardContents(){
//other codes
this.loadingmsg = this.loadingCtrl.create({
content:"Loading contents, please wait..."
});
this.loadingmsg.present();
this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
this.loadingmsg.dismiss().then(()=>{
//other codes to save retrieved data to localstorage.
});
});
}
}
UPDATE
The login method from login page
loginUser(){
this.loading=this.loadingctrl.create({
content:"Logging in, please wait..."
});
this.loading.present();
this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
this.loading.dismiss();
if(data.status =="ok"){
this.navctrl.push(DashboardPage).then(()=>{
const index = this.viewCtrl.index;
this.navctrl.remove(index);
});
}else{
//show error alert
}
}, err =>{
this.loading.dismiss();
});
}
My Ionic and cordova version information
Ionic Framework: 3.5.0
Ionic App Scripts: 1.3.9
Angular Core: 4.1.3
Angular Compiler CLI: 4.1.3
Node: 6.10.3
OS Platform: Windows 10
Cordova Version: 6.5.0
I am currently using loading in my project and it works well in all case. To ensure loading will always dismiss you need to add some code:
1. duration, dismissOnPageChange
let loading = this.loadingCtrl.create({
content: "",
duration: 5000, //ms
dismissOnPageChange: true
})
2. dissmis when ajax call success or error:
.subscribe(success=>{
//some code
loading.dismiss();
},error=>{
//some code
loading.dismiss();
})
It may be due to the this reference inside your subscribe method. I would try declaring loadingmsg locally and removing this.
loadDashboardContents(){
//other codes
let loadingmsg = this.loadingCtrl.create({
content:"Loading contents, please wait..."
});
loadingmsg.present();
this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
loadingmsg.dismiss().then(()=>{
//other codes to save retrieved data to localstorage.
});
});
}
I have a submit button and upon pressing the button I display a loading image and then draw table and then draw google chart.
code for google chart (this works - verified it standalone):
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['corechart']});
</script>
<script type='text/javascript'>
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic', 'Finland', 'France', 'Germany'],
['ENG 2001', 1336060, 3817614, 974066, 1104797, 6651824, 15727003],
['ENGLISH 2002', 1538156, 3968305, 928875, 1151983, 5940129, 17356071],
['ENGLISH2003', 1576579, 4063225, 1063414, 1156441, 5714009, 16716049]
])
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {title:'Yearly Coffee Consumption by Country',
width:1000, height:600,hAxis: {title: 'Year'}, isStacked:true}
);
}
//google.setOnLoadCallback(drawVisualization);
</script>
code for loading image when pressing a submit button
<script type="text/javascript">
// Get the instance of PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Add initializeRequest and endRequest
prm.add_initializeRequest(prm_InitializeRequest);
prm.add_endRequest(prm_EndRequest);
// Called when async postback begins
function prm_InitializeRequest(sender, args) {
//Display the loading image
var panelProg = $get('divImage');
panelProg.style.display = '';
}
// Called when async postback ends
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$(document).ready(function () {
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
//draw google chart (doesnt work)
google.setOnLoadCallback(drawVisualization);
//or even doesnt work (assume comment out for google.setOnLoadCallback(drawVisualization);
drawVisualization();
});
}
</script>
my submit button is under update panel (to make partial-page refresh for loading image to show user that it's fetching data from server). with this code, i am able to show loading image and display table but not google chart. I am not sure how I can call google chart draw function to make google chart appear. I have looked at several posting but couldnt find anything that works for my case. I even tried google.load('visualization', '1', { packages: ['corechart'], "callback":drawVisualization}) but it didnt work. I am so lost at this point. what is the correct way to make google chart work under update panel/PageRequestManager? Thanks!
I don't think you need (or want) to use a document ready handler in your prm_EndRequest function. Try this instead:
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
drawVisualization();
}
To make sure the Viz API code doesn't try to run before the API is finished loading, you should make sure to wrap whatever code you use to hook up the AJAX call to your button inside a callback from the google loader.
I have seen this question in SO several times. Most of cases user called facebook js (all.js) twice or did not provide the application id. But my case is different. I have included all.js once and I also have set application id. But still I am getting this error "FB.login() called before calling FB.init()" when I click the login button. The markup for login button is as follows
<fb:login-button autologoutlink="true" perms="email,user_birthday,user_about_me,publish_stream"></fb:login-button>
And the javascript codes are
<script type="text/javascript">
FB.init({appId: '${section.parameters['facebook.app.id']}', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
//logout();
});
function setFacebookStatus(form) {
var status = $('#comment-form-body').val();
var params = {};
params['message']= status;
params['link'] = '${article.url}';
FB.api('/me/feed', 'post',params, function(response) {
if (!response || response.error) {
alert('Error occured');
}
else {
alert('<fmt:message key="comment.form.facebook.success" />');
$("#facebookComment").overlay().close();
form.submit();
}
});
}
</script>
I have added all.js in the header of my html page. I am really pissed off this issue. I would be very grateful if you help me.
Edit
One more thing to mention. Sometimes it works and sometimes it shows me the warning. Say I was logged in to facebook from another tab and then I logged out from facebook. Then I refresh my website page that has the facebook integration. Then I get the warning. Main problem is that sometimes it is working sometimes not.
I have modified my javascript as follows and now it is working.
$(function() {
window.fbAsyncInit = function() {
FB.init({appId: '${section.parameters['facebook.app.id']}', status: true, cookie: true, xfbml: true});
};
$('body').append('<div id="fb-root"></div>');
$.getScript(document.location.protocol + '//connect.facebook.net/en_US/all.js');
})
setFacebookStatus function remain same. Adding those scripts on document ready removes the problem of facebook javascript warning and non deterministic login behavior. My guess is that on document ready initialization of FB scripts ensures execution of all calls in required order.