How to use $interval for continuous polling in Angular? - javascript

In my Angular code, I have a code for long polling, that looks like this
var request = function() {
$http.post(url).then(function(res) {
var shouldStop = handleData(res);
if (!shouldStop()) {
request()
}
};
}
request();
The function gets called immediately after the page load.
However, now I am trying to set up testing in Protractor and I got this error message
Failed: Timed out waiting for Protractor to synchronize with the page after 11 seconds. Please see
https://github.com/angular/protractor/blob/master/docs/faq.md. The following tasks were pending:
In the docs, I read the following:
Before performing any action, Protractor asks Angular to wait until the page is synchronized. This means that all timeouts and http requests are finished. If your application continuously polls $timeout or $http, it will never be registered as completely loaded. You should use the $interval service (interval.js) for anything that polls continuously (introduced in Angular 1.2rc3).
How should I edit my code to use $interval? I thought that interval is an angular wrapper for window.setInterval, I am not sure how to use that for long polling.

Oh, the $interval thing in the docs belongs to the $timeout, not to the $http.
Well, I will just throw away Angular's $http and will just use fetch (with additional $rootScope.$apply and JSON deserialization) to do the same thing

Related

Finding the UI element in protractor is not consistent. Working with localhost and not with the server

Here is the code I am using expect(element(by.id('title')).getAttribute('value')).toMatch('Sample Title')
in local machine it is working perfectly fine and on server it is not with the following error.
Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds. This may be because the current page is not an Angular application. Please see the FAQ for more details: https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular
While waiting for element with locator - Locator: By(css selector, *[id="title"])
and surprisingly sometimes these tests are working on server when I execute them alone.
to add to the question. I observed that protractor is able to find only one element in the tests and all the remaining are ignored with the error as above.
what could be the solution for this?
That could be application issue. Sometimes it happens that angular never reports to protractor that all tasks are done, so you might get this timeout error that you have.
http://www.protractortest.org/#/timeouts
AngularJS If your AngularJS application continuously polls $timeout or
$http, Protractor will wait indefinitely and time out. You should use
the $interval for anything that polls continuously (introduced in
Angular 1.2rc3).
Angular For Angular apps, Protractor will wait until the Angular Zone
stabilizes. This means long running async operations will block your
test from continuing. To work around this, run these tasks outside the
Angular zone. For example:
this.ngZone.runOutsideAngular(() => { setTimeout(() => {
// Changes here will not propagate into your view.
this.ngZone.run(() => {
// Run inside the ngZone to trigger change detection.
}); }, REALLY_LONG_DELAY); }); As an alternative to either of these options, you could disable waiting for Angular, see below.
As said in the error, it seems your app is not an angular. Isn't it?
If so, you need to use it:
browser.waitForAngularEnabled(false);

Calling same service multiple times, sign of bad design?

I'm in the process of building out a fairly large Angular app and I've stuck to the design of building 'thin' controllers. My controllers don't try to do too much, they are each focused on one piece of functionality within my app.
There, however, is certain data that is 'shared' between controllers. I aim to avoid using $rootScope and instead rely on services to share data and 'state'.
When looking in the 'Network' tab of Chrome Dev Tools I notice certain services being called half a dozen times. So my question is, is this bad design? Are multiple calls to the same service within an Angular app not the 'Angular way' to do things? Note: these service calls take ~ 20ms each, so clearly not much of a performance hit...so far.
I'd suggest reducing the number of unnecessary HTTP requests that you're making for two reasons:
In production environments, these HTTP requests may take more time to complete when factors such as network latency or server load are taken into account; and
will delay the loading of any other assets such as images (assuming that they're coming from the same domain).
An approach that I've used when dealing with the scenario that you've described is to cache the response/data from the API in the service. So, on subsequent calls to the service, the data can be pulled from the cache rather than the API.
See a brief example below:
angular.module('app', ['ngResource'])
.factory('Post', ['$resource', function($resource) {
var posts = [];
var service = {
all: all
}
return service;
function all() {
// if cached posts exist, return those. Otherwise, make call to external API.
if (posts.length > 0) {
return posts.$promise;
} else {
posts = $resource('http://localhost/api/v1/posts.json').query();
return posts.$promise;
}
}
}]);
Note: you'll also have to consider resetting your cache however this would be dependent on your application logic.
Hope this helps!
L
In this case you should look to use $cacheFactory to reduce service calls.
Are you talking about REST services? Are you making $http calls in order to share data and state between controllers?
Why not use service/factory in Angular?
What you need is
1. DataCache service/factory - which will store your response from server
2. A directive - to call these services. include it in your different views
3. Now inside your service which is responsible for making http call first check if data is available in cache if yes return promise of stored data (you can use $q.when) if not make service call.
I have mentioned point 2 since I am assuming inside your various controller you must be doing something like AbcFactory.getItem().then() to avoid duplication of this code as you never know when the requirement will change since change is the only constant during development ;)

AngularJS + Android 4.2: very slow to react

Our web app is built with AngularJS v1.2.26 We're troubleshooting an issue that only seems to happen on older Android browsers, specifically 4.2...
In short, asynchronous things are happening ~600% slower than they should. For example, we show an error message in response to a failed HTTP request. The service in charge of making the request has a variable which holds status messages. Then a controller watches it like this:
// Status msg ctrl
var statusCtrl = app.controller('statusCtrl', function($scope, updateService, $timeout) {
$scope.message = false;
//watch for status messages
$scope.$watch(function () { return updateService.loadingTroubleMsg; },
function (value) {
$scope.message = value;
}
);
});
In other browsers this works perfectly. The http request fails and then the message appears right away. On the Android browser (which the client is running from a USB) the message shows up ~20 minutes later.
I have a couple theories:
The promise is taking a very long time to be resolved,
The $watch is happing in slow motion.
The http request is taking a reallllly long time to timeout.
There are no visible errors, and everything else seems to work. Unfortunately, I do not have the exact USB Android device in my position, which makes troubleshooting more difficult.
Why would this happen? Are any of my theories more plausible then the others? Any advice on how to get to the bottom of this is welcome.
It turned out to be #3. I added a "timeout" limit to the $http config settings and it started responding normally. I don't know why this only mattered on Android 4.2. I'm guessing it's related to its lack of (native) support for promises.

Angular bootstrap lifecycle: Run code after full load

Angular defines a run() block for an application module. This runs after config() and before any controllers and directives are loaded.
Is there a step in the lifecycle to run something after all controllers, directives, services, etc are loaded?
I need this in order to broadcast a message in my authorization pubsub service, and I want to ensure that everything is loaded before I publish the message. While I can check authentication in the run block (basically, just checking localstorage for a JWT via my authentication service), if I publish in the run() block I can't be sure if everything has loaded. I'm wondering if Angular exposes anything like this or whether I need to find a different solution.
Thanks!
An optional answer, taken from here
You can use a custom postDigest callback. if you need only the first postDigest callback, add a flag to indicate it happened
function postDigest(callback){
var unregister = $rootScope.$watch(function(){
unregister();
$timeout(function(){
callback();
postDigest(callback);
},0,false);
});
}
postDigest(function(){
console.log('do something');
})

Syncronizing Session data with other angular directives and controllers

In my AngularJS application, I have a Session service object that contains stuff like the current user, their preferences, the current company they belong to, and the current theme that they are using. Many places in my application refer to the Session service when they need to get at this data.
Because these variables are in a service, I cannot use scope watches to detect changes. So instead, I've decided to use the observer pattern. Various places in the application, such as other services, directives, controllers, etc. will register themselves with the Session service and provide a callback to be executed whenever the Session changes.
For example, if the user changes their theme, the <style> element in index.html that uses a custom directive will be notified, and it will recreate all of the overriding css rules for the new colors.
For another example, whenever the user's avatar is updated, the main menu bar controller will be notified to refresh and redraw the avatar. Stuff like this.
Obviously the data in Session has to be refreshed at least once before the various controllers, directives, etc. use it. The natural place to ask the Session service to get its session data was in a run block for the application-level module. This works pretty well, but I don't think it's the best place either.
One problem I have noticed is that when Firebug is open, the asynchronous nature of things loading causes ordering issues. For example, the directive that runs on the <style> element will run AFTER the Session service has refreshed in the application's run block... which means the theme will not get updated after pressing F5 because the callback is registered after the initialization of the data occured. I would have to call a manual refresh here to keep it in sync, but if I did that, it may execute twice in the times where the order is different! This is a big problem. I don't think this issue is just related to Firebug... it could happen under any circumstance, but Firebug seems to cause it somewhat consistently, and this is bad.
To recap... This asynchronous ordering is good:
Theme Directive registers callback to Session
Menu Bar application controller registers callback to Session
Session.refresh() is called in .run block.
This asynchronous ordering is bad:
Menu Bar application controller registers callback to Session
Session.refresh() is called in .run block.
Theme Directive registers callback to Session, but callback does not get executed since Session.refresh() was already executed.
So rather than use the observer pattern, or refresh the Session state via a run block, what the best way to design the services, etc. so that the session data will ALWAYS get refreshed after (or maybe before) the various other parts of the application require it? Is there some kind of event I can hook into that gets executed before directives and controllers are executed instead of the run block?
If my approach is generally sound, what can I add to it to really make it work the way it should?
Thanks!
In angular.js you have 2 way of using global variables:
use a $rootScope
use a service
Using $rootScope is very easy as you can simply inject it into any controller and change values in this scope. All global variables have problems!
Services is a singletons(What you need)!
I think in your case you can use
$rootScope
And
$scope.$watch
Great answer
Is there a reason you can't access the variables directly like this:
app.factory('SessionService', function() {
var items = {
"avatar": "some url"
};
return items;
});
var MainController = [$scope, 'SessionService', function($scope, SessionService){
$scope.session = SessionService;
$scope.modifyAvatar = function(url){
$scope.session.avatar = "some new url";
};
}];
var HeaderController = [$scope, 'SessionService', function($scope, SessionService){
$scope.session = SessionService;
// You probably wouldn't do this, you would just bind
// to {{session.avatar}} in your template
$scope.getAvatar = function(){
return $scope.session.avatar;
};
}];

Categories

Resources