ionic refresh with jsdata doesnt seem to work - ionic-framework

My ionic app uses jsdata datastore for caching http://www.js-data.io/docs/home
. I am trying to implement the pull to refresh feature in my app using ion-refresher directive.
The doRefresh doesnot seem to make a Get Call at all. When I click on Pull to refresh, all the console.log messages in the code below get executed. However, if I check the Network's tab, I dont see a Get call being made at all.
No data gets refreshed, nor do I get any error. I am not sure why this is happening or what I am doing wrong.
My code:
HTML:
<ion-refresher
pulling-text="Pull to refresh..."
on-refresh="doRefresh()">
</ion-refresher>
Controller:
.controller('ProfileInfo', function($scope, Profile) {
$scope.load = function() {
$scope.error = undefined;
Profile.findAll().then(function(response) {
$scope.Profile = response[0];
}).catch(function(err) {
$scope.error = err;
});
};
$scope.load();
$scope.doRefresh = function() {
console.log("hi")
$scope.error = undefined;
$scope.Profile = [];
Profile.findAll().then(function(response) {
console.log($scope.Profile)
$scope.Profile = response[0];
console.log($scope.Profile)
console.log("Done")
}).catch(function(err) {
console.log("err", err)
$scope.error = err;
}).finally(function(){
console.log("in finally")
$scope.$broadcast('scroll.refreshComplete');
});
};
});

Inside your doRefresh method, you need to pass bypassCache: true to findAll all to force it try make a new request, e.g.
var query = {};
var options = {
bypassCache: true
};
Profile.findAll(query, options).then(...);
Read more about the behavior of DS#findAll in JSData 2.x.

Related

How I get contain of a href and img from cgv website using axios and jsdom

I have a problem when i wanto target and get contain a href and img from this website https://www.cgv.id/en/movies/now_playing but i always wrong to get it. This is may code:
const { default: axios } = require("axios");
const { JSDOM } = require("jsdom");
(async () => {
try {
const { data } = await axios.get(
"https://www.cgv.id/en/movies/now_playing"
);
let dom = new JSDOM(data).window.document;
let list = [...dom.getElementsByClassName('movie-list-body').querySelectorAll('li')]
list = list.map(v => v.document.querySelectorAll('li a[href]').textContent.trimEnd())
console.log(list);
} catch (error) {
console.log(error);
}
})()
My code is error. How i repair it and can target to get contain a href and img it?
There are couple of issues with using JSDOM there, especially the way you are using it.
Firstly the website in question does not have any markup for the DOM element with the class name movie-list-body as you retrieve it using Axios
On further inspection I realised they are using a jQuery AJAX call to retrieve all the links and images from a JSON file.
Following is the script they are using to do so.
<script>
$(function() {
$.ajax({
type: 'GET',
url: '/en/loader/home_movie_list',
success: function(data) {
$('.movie-list-body').html(data.now_playing);
$('.comingsoon-movie-list-body').html(data.comingsoon);
$('.lazy').lazy({
combined: true
});
}
});
});
</script>
In my opinion you should just use that JSON file. However, if you still want to use JSDOM following are some of the approaches.
Given that the site requires resource processing, if you want to parse the whole page using JSDOM you will have to pass the options as mentioned in the JSDOM documentation as follows:
const options = {
contentType: "text/html",
includeNodeLocations: true,
resources: "usable",
};
let dom = new JSDOM( data, options ).window.document;
These options will allow the JSDOM to load all the resources including jQuery that will in-turn allow the Node to make the AJAX call, populate the element and then in-theory you extract the links. However, there are some CSS files that JSDOM is unable to parse.
Therefore, I think your best bet is to do something along the following lines:
const { default: axios } = require("axios");
const { JSDOM } = require("jsdom");
(async () => {
try {
const data = await axios.get(
"https://www.cgv.id/en/loader/home_movie_list"
);
const base_url = 'https://www.cgv.id';
var dom = new JSDOM(data.data.now_playing).window.document;
var lists = [ ... dom.getElementsByTagName('ul')[0].children ]
var list = lists.map( list => [ base_url+list.firstChild.href, list.firstChild.firstChild.dataset.src ] );
console.log( list );
} catch (error) {
console.log(error);
}
})()
Note:
There is only one catch with the approach mentioned above which is that if the author of the website changes the endpoint for the JSON file, your solution will stop working.

Mapbox GL JS: Style is not done loading

I have a map wher we can classically switch from one style to another, streets to satellite for example.
I want to be informed that the style is loaded to then add a layer.
According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.
That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.
My code is:
mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [5,45.5],
zoom: 7
});
map.on('load', function () {
loadRegionMask();
});
map.on('styledataloading', function (styledata) {
if (map.isStyleLoaded()) {
loadRegionMask();
}
});
$('#typeMap').on('click', function switchLayer(layer) {
var layerId = layer.target.control.id;
switch (layerId) {
case 'streets':
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
break;
case 'satellite':
map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
break;
}
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'regions.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadRegionMask() {
loadJSON(function(response) {
var geoPoints_JSON = JSON.parse(response);
map.addSource("region-boundaries", {
'type': 'geojson',
'data': geoPoints_JSON,
});
map.addLayer({
'id': 'region-fill',
'type': 'fill',
'source': "region-boundaries",
'layout': {},
'paint': {
'fill-color': '#C4633F',
'fill-opacity': 0.5
},
"filter": ["==", "$type", "Polygon"]
});
});
}
And the error is:
Uncaught Error: Style is not done loading
at t._checkLoaded (mapbox-gl.js:308)
at t.addSource (mapbox-gl.js:308)
at e.addSource (mapbox-gl.js:390)
at map.js:92 (map.addSource("region-boundaries",...)
at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?
1. Listen styledata event to solve your problem
You may need to listen styledata event in your project, since this is the only standard event mentioned in mapbox-gl-js documents, see https://docs.mapbox.com/mapbox-gl-js/api/#map.event:styledata.
You can use it in this way:
map.on('styledata', function() {
addLayer();
});
2. Reasons why you shouldn't use other methods mentioned above
setTimeout may work but is not a recommend way to solve the problem, and you would got unexpected result if your render work is heavy;
style.load is a private event in mapbox, as discussed in issue https://github.com/mapbox/mapbox-gl-js/issues/7579, so we shouldn't listen to it apparently;
.isStyleLoaded() works but can't be called all the time until style is full loaded, you need a listener rather than a judgement method;
Ok, this mapbox issue sucks, but I have a solution
myMap.on('styledata', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
I mix both solutions.
I was facing a similar issue and ended up with this solution:
I created a small function that would check if the style was done loading:
// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
if (map.isStyleLoaded()) {
return true; // When it is safe to manipulate layers
} else {
return false; // When it is not safe to manipulate layers
}
}
Then whenever I swap or otherwise modify layers in the app I use the function like this:
function swapLayer() {
var check = checkIfMapboxStyleIsLoaded();
if (!check) {
// It's not safe to manipulate layers yet, so wait 200ms and then check again
setTimeout(function() {
swapLayer();
}, 200);
return;
}
// Whew, now it's safe to manipulate layers!
the rest of the swapLayer logic goes here...
}
Use the style.load event. It will trigger once each time a new style loads.
map.on('style.load', function() {
addLayer();
});
My working example:
when I change style
map.setStyle()
I get error Uncaught Error: Style is not done loading
This solved my problem
Do not use map.on("load", loadTiles);
instead use
map.on('styledata', function() {
addLayer();
});
when you change style, map.setStyle(), you must wait for setStyle() finished, then to add other layers.
so far map.setStyle('xxx', callback) Does not allowed. To wait until callback, work around is use map.on("styledata"
map.on("load" not work, if you change map.setStyle(). you will get error: Uncaught Error: Style is not done loading
The current style event structure is broken (at least as of Mapbox GL v1.3.0). If you check map.isStyleLoaded() in the styledata event handler, it always resolves to false:
map.on('styledata', function (e) {
if (map.isStyleLoaded()){
// This never happens...
}
}
My solution is to create a new event called "style_finally_loaded" that gets fired only once, and only when the style has actually loaded:
var checking_style_status = false;
map.on('styledata', function (e) {
if (checking_style_status){
// If already checking style status, bail out
// (important because styledata event may fire multiple times)
return;
} else {
checking_style_status = true;
check_style_status();
}
});
function check_style_status() {
if (map.isStyleLoaded()) {
checking_style_status = false;
map._container.trigger('map_style_finally_loaded');
} else {
// If not yet loaded, repeat check after delay:
setTimeout(function() {check_style_status();}, 200);
return;
}
}
I had the same problem, when adding real estate markers to the map. For the first time addding the markers I wait till the map turns idle. After it was added once I save this in realEstateWasInitialLoaded and just add it afterwards without any waiting. But make sure to reset realEstateWasInitialLoaded to false when changing the base map or something similar.
checkIfRealEstateLayerCanBeAddedAndAdd() {
/* The map must exist and real estates must be ready */
if (this.map && this.realEstates) {
this.map.once('idle', () => {
if (!this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
this.realEstateWasInitialLoaded = true
}
})
if(this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
}
}
},
I ended up with :
map.once("idle", ()=>{ ... some function here});
In case you have a bunch of stuff you want to do , i would do something like this =>
add them to an array which looks like [{func: function, param: params}], then you have another function which does this:
executeActions(actions) {
actions.forEach((action) => {
action.func(action.params);
});
And at the end you have
this.map.once("idle", () => {
this.executeActions(actionsArray);
});
I have created simple solution. Give 1 second for mapbox to load the style after you set the style and you can draw the layer
map.setStyle(styleUrl);
setTimeout(function(){
reDrawMapSourceAndLayer(); /// your function layer
}, 1000);
when you use map.on('styledataloading') it will trigger couple of time when you changes the style
map.on('styledataloading', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});

Chrome App FileReader

I'm trying to make use of the file system API in a Chrome App. I've tried all the sample code I can find and can't get a simple text file to read. I'm logging almost every step, and what seems to happen (or not happen) is everything stops the first time I reference a file reader object. It creates just fine, because I can log the .readyState, but after that I can't seem to even set an onload()event or execute a .readAsText().
Here's what I'm calling from a button:
function clickButton(){
chrome.fileSystem.chooseEntry({type: 'openFile', acceptsMultiple: false}, function(FileEntry){
if(chrome.runtime.lastError) {console.warn("Warning: " + chrome.runtime.lastError.message);}
else{
console.log(FileEntry);
var thing = new FileReader();
console.log(thing.readyState);
thing.onloadstart(function(){
console.log("Started loading " & FileEntry);
});
console.log("added onloadstart");
console.log(thing.readyState);
console.log(thing);
thing.readAsText(FileEntry);
console.log(thing.readyState);
console.log(thing.result);
}
});
document.getElementById("status").innerHTML = "I did something";
}
I did read somewhere that Chrome doesn't allow access to local files, but the chrome apps seem to be different. At least, the documentation seems to suggest that.
The only thing I end up with in my console is the FileEntry object.
https://developer.chrome.com/apps/app_storage#filesystem
I've used the example code right from the above link and still can't get it right. Anyone else have this issue or know what I'm doing wrong?
There is a difference between a FileEntry and a File. You need to call FileEntry's .file() method. So, replace
thing.readAsText(FileEntry);
with
FileEntry.file(function(File) {
thing.readAsText(File)
})
https://developer.mozilla.org/en-US/docs/Web/API/FileEntry#File
Try this code...
<!doctype html>
<html>
<script>
function handle_files(files) {
for (i = 0; i < files.length; i++) {
file = files[i]
console.log(file)
var reader = new FileReader()
ret = []
reader.onload = function(e) {
console.log(e.target.result)
}
reader.onerror = function(stuff) {
console.log("error", stuff)
console.log (stuff.getMessage())
}
reader.readAsText(file) //readAsdataURL
}
}
</script>
<body>
FileReader that works!
<input type="file" multiple onchange="handle_files(this.files)">
</body>
</html>
I've written a function to extract text from a file.
function getFileEntryText(fileEntry) {
return new Promise(function (resolve, reject) {
fileEntry.file(function (file) {
var fileReader = new FileReader();
fileReader.onload = function (text) {
resolve(fileReader.result);
};
fileReader.onerror = function () {
reject(fileReader.error);
};
fileReader.readAsText(file);
});
});
}
You can invoke this method like so:
getFileEntryText(fileEntry).then(function(text) {
// Process the file text here
}, function(error) {
// Handle the file error here
});
One thing I'm grappling with when working with the FileSystem is that every call is asynchronous. Having multiple levels of nested callbacks can make for code that's hard to read. I'm currently working around this by converting everything I can to a Promise.
for anyone who is interested, here's my final (working) code, complete with all the console.log()'s I needed to follow all those callbacks.
var chosenEntry = null;
function clickButton(){
console.log("Button clicked");
var accepts = [{
mimeTypes: ['text/*'],
extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf']
}];
chrome.fileSystem.chooseEntry({type: 'openFile', accepts: accepts}, function(theEntry) {
if (!theEntry) {
output.textContent = 'No file selected.';
return;
}
// use local storage to retain access to this file
chrome.storage.local.set({'chosenFile': chrome.fileSystem.retainEntry(theEntry)});
console.log("local data set. calling loadFileEntry");
loadFileEntry(theEntry);
console.log("loadFileEntry called, returned to clickButton()");
});
}
function loadFileEntry(_chosenEntry) {
console.log("entered loadFileEntry()");
chosenEntry = _chosenEntry;
chosenEntry.file(function(file) {
readAsText(chosenEntry, function(result) {
console.log("running callback in readAsText");
document.getElementById('text').innerHTML = result;
console.log("I just tried to update textarea.innerHTML");
});
});
console.log("added function to chosenEntry.file()");
}
function readAsText(fileEntry, callback) {
console.log("readAsText called");
fileEntry.file(function(file) {
var reader = new FileReader();
console.log("Created reader as FileReader");
reader.onload = function(e) {
console.log("called reader.onload function");
callback(e.target.result);
};
console.log("calling reader.readAsText");
reader.readAsText(file);
});
}

Problems using $ionicLoading and modal view

Something strange is happening to my app. I'm using $ionicLoading to show and hide the loading template when I go to a page of my app. Everything works fine in the current page after the loading template appears, but if I open a modal page in the current view, it'll be showed but I won't be able to interact with the modal view, everything seems frozen. The app continues running but I can't select anything in the modal. I'm pretty sure that $ionicLoading is what is making this problem appears because if I eliminate it, everything works fine.
So, How could I solve it?.
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $http, $ionicPopover, $rootScope,$ionicLoading) {
$ionicModal.fromTemplateUrl('templates/nuevoEvento.html', {
scope: $scope,
animation: 'slide-in-right'
}).then(function(modal) {
$scope.modalEvento = modal;
});
// Open the login modal
$scope.evento = function() {
$scope.modalEvento.show();
};
$scope.closeEvento = function() {
$scope.modalEvento.hide();
};
$scope.showLoading = function() {
$ionicLoading.show({
template: 'Loading...'
});
};
$scope.hideLoading = function(){
$ionicLoading.hide();
};
})
.controller('EventosCtrl', function($scope, $stateParams, $http, $timeout,$ionicLoading ) {
$scope.init=function(){
$scope.showLoading();
$http({method: 'GET', url: BASEPATH + '/eventos'})
.success(function(data){
$scope.hideLoading();
$scope.eventos = data;
console.log(data);
var evLeft = [];
var evRight = [];
for(var i = 0; i < data.length; i = i + 2){
evLeft.push(data[i]);
if(data[i+1]){
evRight.push(data[i+1]);
}
}
$scope.tarjetasLeft = evLeft;
$scope.tarjetasRight = evRight;
})
You said you cannot interact with the modal view.
Try the option noBackdrop (or even maybe hideOnStateChange)
More info at the docs

Delete form data for subsequent ajax calls

I have a link that opens a dialog modal asking for a date. When they click submit, javascript takes the form data, generates an ajax call, and returns the response. This works no problem. However if I immediately click the same link again and submit a new date in the form, I get the results from my first ajax POST.
Essentially, subsequent ajax calls are using the original POST data and nothing new. Code has alerts for troubleshooting. Im assuming im setting some var thats not getting reset, but thought this event handler was canceled with the "off", then re-added immediately after and the vars would be in scope to that function alone.
<script>
//Modal submit
$(document).off('click', '#SubmitAllChecks');
$(document).on('click', '#SubmitAllChecks', function(e) {
e.preventDefault();
var form = $('#AllChecks');
var url = form.attr('action');
var method = form.attr('method');
var data = form.serializeArray();
$.each(data, function(k,v) {
alert(v.name + ' : ' + v.value);
});
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
beforeSend: function() {
//add load indicator
window.erpui.startload();
},
success: function(data) {
alert('xhr complete');
$.each(data, function() {
alert(this.value + ' data');
if (this.value == 'error' && this.msg != '') {
window.erpui.endload();
window.erpui.notify.error(this.msg);
window.erpui.notify.commit();
}
else if (this.value == 'success') {
window.erpui.endload();
window.erpui.notify.success(this.msg);
window.erpui.notify.commit();
$('.ui-dialog').remove();
//window.location.href="{% url all_checks %}";
//window.location.reload();
}
});
},
error: function() {
alert('error');
//remove load indicator
window.erpui.endload();
}
});
});
</script>