Sometimes in my application a HTTP call to get a list or some sort of resource will fail for no obvious reason, however, if it's re-fired straight away it will work.
Is there a way to configure all HTTP calls to say something along the lines of
if ( has no success after 2-3 seconds ) {
re-fire HTTP call...
}
I find in my application (which is ASP.NET) that often times I have to double click a link to make a page load. This I feel is probably the same issue with the HTTP calls in the code. Not sure as to how to trace or de-bug this sort of problem and if anyone had any thoughts on that you would really be helping me out!
Any advice much would be greatly appreciated.
Thanks!
you can do it using an $httpInterceptor, maybe a god solution could be fix the problem instead of that, by the way, there is an example:
this wonderful post maybe help you to understand $http interceptors
(function(window, angular, APP) {
var MAX_ERRORS = 1; // after that: giving up
function FeelAgainConfig($httpProvider) {
$httpProvider.interceptors.push(function FeelAgainInterceptor($q, $http) {
var interceptors = {};
interceptors.responseError = function FeelAgainInterceptorResponseError(data) {
// implement an error counter that helps you to not fall in an infinite call stack
if(data.errorCount >= MAX_ERRORS) {
return $q.reject(data);
};
// Perform the request again;
};
return interceptors;
});
}
APP
.config(FeelAgainConfig)
;
})(window, window.angular, window.angular.module('feelAgain$http', []));
If you're looking to change the behaviour of the $http service in Angular, then there is a way. This post describes it briefly, and here's the important bits citated from the post.:
For example if you are making a late global alteration to a large
ongoing project, or want to change the behavior of XHR requests in
third party code that can't be altered. In these circumstances you
might use $provide.decorator() to globally replace $http with a
wrapped version.
By wrapping the $http servie you have the option to change behaviour.
It sounds like you have a different problem though since you need to trigger calls twice, I suggest you solve that first.
Related
I am having difficulty in understanding how to use the jQuery smart wizard.
I have managed to get it going with static html for my first three tabs but I now want to add another tab which uses an ajax call to get the data based on the data I have collected in the previous tabs.
I know there are callback functions for leaving and entering steps but the documentation is unclear on how to use them (or it maybe I don't understand enough jQuery/JavaScript to correctly interpret the documentation)
The way I read it is I would use
$("#smartwizard").on("stepContent", function(e, anchorObject, stepIndex, stepDirection) {
// if this is the correct step index then
// do my ajax call using a promise
// (Which I do not understand fully how to do.
// I have never used a promise before.)
// and return my html. (Where is the html going to be put? is it the 'tabpanel'?)
return myHTMLfromtheajaxcall;
// else do nothing
// How do I stop it overriding the existing content?
// Do I return '' or false or what?
});
What and where do the parameters for the function come from. What is 'e'? What is 'anchorObject'? The other parameters are self explanatory.
I hope somebody can explain things in simple terms with some examples.
Thank you in advance.
We have a use case where we need to block Drupal's core ajax error handling from alerting users (we're handling the error reporting on our own). Previously another developer had commented out a line in the core ajax.js file, to prevent Drupal from spawning the alert box, but I'd like to handle it without touching core.
From the core, drupal.js:
/**
* Displays a JavaScript error from an Ajax response when appropriate to do so.
*/
Drupal.displayAjaxError = function (message) {
// Skip displaying the message if the user deliberately aborted (for example,
// by reloading the page or navigating to a different page) while the Ajax
// request was still ongoing. See, for example, the discussion at
// http://stackoverflow.com/questions/699941/handle-ajax-error-when-a-user-
// clicks-refresh.
if (!Drupal.beforeUnloadCalled) {
alert(message);
}
};
My current fix, is to override the Drupal.displayAjaxError function and change the Drupal.beforeUnloadCalled property that determines whether or not to alert the error:
var ajax_error_backup = Drupal.displayAjaxError;
Drupal.displayAjaxError = function (message) {
Drupal.beforeUnloadCalled = true;
ajax_error_backup(message);
};
My question, is whether or not this is an appropriate fix? I know that I could also override the function and just leave it empty - costing fewer lines, and not invoking another call to the original function (and saving the object I've created by backing up the original in ajax_error_backup).
Am I adding complexity to keep things tidy, or should I just override with:
Drupal.displayAjaxError = function (message) {
//empty
};
To clarify - the desire is to never have this ajax alert occur, so there's not functional difference between my desire to keep things neat/tidy, and just overriding the function with a blank one - there isn't a case where want this alert to succeed.
Thanks in advance for helping this old dog think through something with fresh eyes.
In this case, there isn't one option that seems to be clearly better than the other. It should be handled on a case by case basis, and in this case, either of the methods really is adequate.
I personally opted for using the slightly more expensive method of overriding the function and calling it back, because I felt that it might be somewhat more future-proof:
var ajax_error_backup = Drupal.displayAjaxError;
Drupal.displayAjaxError = function (message) {
Drupal.beforeUnloadCalled = true;
ajax_error_backup(message);
};
If Drupal were to extend the function on their end in the future, there might be another condition that we wouldn't want to override.
Overriding with the empty function would be the cheapest, but would also potentially be a bit heavy handed.
It seems that either approach is valid, and is probably best handled case-by-case.
I'm new to Meteor.js, so hopefully this is an inability on my part rather than a limitation of the platform because it's pretty amazing otherwise.
What I'm trying to achieve is pretty straightforward: run Javascript whenever a template helper gets updated with new data (but not from the db!).
A simple example scenario could be this: A user makes a request to get some images. But rather than the images just "popping up", they should be hidden and fadein once they've been fully loaded (among other things like positioning them, etc.).
In other words, right after the helper receives new data, a function should run to do something with that data (that can not be done on the server before it is actually rendered).
If the data is from a collection, it's quite easy to achieve this with a subscribe callback.
However, there seems to be no callback for once a helper has rendered the new data.
Yes, it's possible to add a timeout of a few ms, but that's not a clean or reliable solution in my mind, because you obviously never know exactly how long it will need to render.
I've searched through dozens of seemingly related posts, but was not able to find anything that could be considered a "standard" way of achieving this...
Here's a bit of (simplified) example code to illustrate the scenario:
var images = [];
//When showImages is updated with new data from the images array...
Template.gallery.helpers({
showImages: function () {
return images;
}
});
//...this function should fire
function doMagicWork () {
...
}
//Because firing it on the on click event would be too soon,
//as the helper hasn't rendered yet
Template.gallery.events({
"click #fetch_images": function (event) {
Meteor.call("getImagesFromServer", function(error, result) {
images = result.content;
});
}
});
There is a pending feature for adding animation/transition support for UI changes (referenced here)
As an interim solution, you can use Blaze UI hooks. There are quite a few packages that use them. example here and here
In general, , Meteor way is to reduce the amount of boiler plate code. Smooth transition is something of a pattern rather than an individual thing for element and should be treated as such as per meteor philosophy.
I read a lot about Express / SocketIO and that's crazy how rarely you get some other example than a "Hello" transmitted directly from the app.js. The problem is it doesn't work like that in the real world ... I'm actually desperate on a logic problem which seems far away from what the web give me, that's why I wanted to point this out, I'm sure asking will be the solution ! :)
I'm refactoring my app (because there were many mistakes like using the global scope to put libs, etc.) ; Let's say I've got a huge system based on SocketIO and NodeJS. There's a loader in the app.js which starts the socket system.
When someone join the app it require() another module : it initializes many socket.on() which are loaded dynamically and go to some /*_socket.js files in a folder. Each function in those modules represent a socket listener, then it's way easier to call it from the front-end, might look like this :
// Will call `user_socket.js` and method `try_to_signin(some params)`
Queries.emit_socket('user.try_to_signin', {some params});
The system itself works really well. But there's a catch : the module that will load all those files which understand what the front-end has sent also transmit libraries linked with req/res (sessions, cookies, others...) and must do it, because the called methods are the core of the app and very often need those libraries.
In the previous example we obviously need to check if the user isn't already logged-in.
// The *_socket.js file looks like this :
var $h = require(__ROOT__ + '/api/helpers');
module.exports = function($s, $w) {
var user_process = require(__ROOT__ + '/api/processes/user_process')($s, $w);
return {
my_method_called: function(reference, params, callback) {
// Stuff using $s, $w, etc.
}
}
// And it's called this way :
// $s = services (a big object)
// $w = workers (a big object depending on $s)
// They are linked with the req/res from the page when they are instantiated
controller_instance = require('../sockets/'+ controller_name +'_socket')($s, $w);
// After some processes ...
socket_io.on(socket_listener, function (datas, callback) {
// Will call the correct function, etc.
$w.queries.handle_socket($w, controller_name, method_name, datas);
});
The good news : basically, it works.
The bad news : every time I refresh the page, the listeners double themselves because they are in a loop called on page load.
Below, this should have been one line :
So I should put all the socket.on('connection'...) stuff outside the page loading, which means when the server starts ... Yes, but I also need the req/res datas to be able to load the libraries, which I get only when the page is loaded !
It's a programing logic problem, I know I did something wrong but I don't know where to go now, I got this big system which "basically" works but there's like a paradox on the way I did it and I can't figure out how to resolve this ... It's been a couple of hours I'm stuck.
How can I refacto to let the possibility to get the current libraries depending on req/res within a socket.on() call ? Is there a trick ? Should I think about changing completely the way I did it ?
Also, is there another way to do what I want to do ?
Thank you everyone !
NOTE : If I didn't explain well or if you want more code, just tell me :)
EDIT - SOLUTION : As seen above we can use sockets.once(); instead of sockets.on(), or there's also the sockets.removeAllListeners() solution which is less clean.
Try As Below.
io.sockets.once('connection', function(socket) {
io.sockets.emit('new-data', {
channel: 'stdout',
value: data
});
});
Use once instead of on.
This problem is similar as given in the following link.
https://stackoverflow.com/questions/25601064/multiple-socket-io-connections-on-page-refresh/25601075#25601075
I'm trying to work out where the best place to run a long-running load operation is using Durandal.
From what I can tell, the general recommendation for loading data is in the ViewModel's activate method, which is what I usually do - something like:
viewModel.activate = function () {
var loadPromise = myService.loadData();
return $.when(loadPromise).then(function (loadedData) {
viewModel.data(data);
});
};
I know that if I don't return the promise here, then there's usually problems with the bindings - as this question and answer indicates.
However, executing a long running load operation in the activate method makes the app "freeze" while the load operation completes. For example, what if my load was now something like this?
viewModel.activate = function () {
// All loads return a promise
var firstLoad = myService.loadFirstData();
var secondLoad = myService.loadSecondData();
var thirdLoad = myService.loadThirdDataWhichTakesAges();
return $.when(firstLoad, secondLoad, thirdLoad).then(function (one, two, three) {
viewModel.one(one);
viewModel.two(two);
viewModel.three(three);
});
};
In this scenario, the URL is updated to reflect the page which is being loaded, but the page content still shows the previous page (which is what I mean by "freezes").
Ideally, it would be good if the URL should change to the new page, and the page content should show the new page too (even though the data for that page has not yet been returned). Then, as each load operation returns, the relevant part of the page should be updated when the data is bound into the view model.
Is there a recommended way for achieving this inside Durandal?
My current solution is to kick-off the load in the activate method, and then populate the data in the viewAttached method:
var loadPromise;
viewModel.activate = function () {
// All loads return a promise
var firstLoad = myService.loadFirstData();
var secondLoad = myService.loadSecondData();
var thirdLoad = myService.loadThirdDataWhichTakesAges();
loadPromise = $.when(firstLoad, secondLoad, thirdLoad);
// Don't return the promise - let activation proceed.
};
viewModel.viewAttached = function () {
$.when(loadPromise).then(function (one, two, three) {
viewModel.one(one);
viewModel.two(two);
viewModel.three(three);
});
};
It seems to work, but I remember reading somewhere that relying on viewAttached wasn't a good solution. I'm also not sure if there is potential for a race condition since I'm allowing the activate to proceed.
Any other recommendations?
You don't have to return a promise but in that case you must handle this in you knockout bindings so you woun't bind to elements that are undefined. You can try to get rid of that 'return' in activate but add a property indicating if model is still loading. Something like this:
viewModel.isLoading = ko.observable(false);
viewModel.activate = function () {
isLoading(true);
var loadPromise = myService.loadData();
$.when(loadPromise).then(function (loadedData) {
viewModel.data(data);
isLoading(false);
});
};
And then, in your view, you can have a section that shows up when view is still loading and one that shows up when loading is done. Sometinhg like:
<div data-bind:"visible: isLoading()">Loading Data....</div>
<div data-bind:"visible: !isLoading()">Put your regular view with bindings here. Loading is done so bindings will work.</div>
Which version of Durandal are you using? In Durandal 2.0.0pre you would be allowed NOT returning a promise in activate so that the composition of the view (without data) could happen immediately.
You might consider refactoring viewModel.one etc. into a module that returns a constructor function, so that each one, two, three would be responsible for retrieving their own data. That way you first two calls wouldn't have to wait on loadThirdDataWhichTakesAges. That would make sense in scenarios where one, two, three are not heavily depend on each other.
For reference; I posted a similar question on the Durandal Google Group (effectively asking if using activate and viewAttached in this manner is an OK idea) and got this reply from Rob Eisenberg:
That will probably work. The problem is that Knockout will destroy
databindings on elements if the properties are updated and the element
isn't currently in the document. This can happen depending on the
timing of the async code. Because of the way composition worked in
1.x, this would cause problems if you didn't return the promise from your activate function. It should work better in viewAttached, but
depending on the nature of your composition, the view may be attached
to its parent, but still not in the document. It depends on the depth
of the composition. So, you could encounter issues with this too if
you have this in a deeply composed module. Unfortunately, there isn't
a clean way about it in Durandal 1.x due to the knockout behavior. In
Durandal 2.x we have reworked composition so that this problem is
non-existent and returning the promise is no longer necessary (though
you can still do it). Durandal 2.0 will be releasing in about two
weeks.