rootScope functions not being called when using ngIdle - angularjs

I am using the ngIdle library and as the documentation states there are certain methods that you can call to check for user inactivity, and I have put these on the root scope.
app.run(function($rootScope) {
$rootScope.$on('IdleTimeout', function() {
alert('you will be logged out');
});
$rootScope.$on('IdleStart', function () {
alert('test');
});
});
These functions are never being called and I think that it might be a problem more to do with $rootscope rather than the ngidle library.
There are not any errors in console, and the ngidle library is included correctly. Any Ideas?

For me ng-idle works fine using the $rootScope. But I wasted some time waiting for the events to fire until I recognized, that the configuration expects seconds instead of milliseconds ;)
app.config(function(IdleProvider) {
// configure Idle settings
IdleProvider.idle(5); // in seconds!
IdleProvider.timeout(5); // in seconds!
});

I spent some time struggling with this too; none of the events were firing at all. Turns out that you need to call Idle.watch() so that the timing starts.
This isn't well documented; documentation is patchy and none of the examples I saw had this. All looked just like the code you have so I couldn't figure out what's wrong until I saw it in the Getting Started section on the library's GitHub page. It's not explicitly mentioned though, you have to look closely.
.run(function(Idle){
// start watching when the app runs. also starts the Keepalive service by default.
Idle.watch();
});
Then the second catch: once you get auto-logged out once, it will no longer time your session if you login again without reloading the app. You need to call Idle.watch() again from your Login method to reset the timers and start again.

Related

Angular Google Map, lazy loading, second time

I'm using angular-ui.github.io/angular-google-maps/
I use the recommended lazy loading technique, I have this in my app.js:
.config(function(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
// key: 'your api key',
v: '3.20' //defaults to latest 3.X anyhow
//libraries: 'weather,geometry,visualization'
});
})
And at some point in my controller, I execute this:
var uiGmapGoogleMapApiTimer = $timeout(function() {
reject("uiGmapGoogleMapApi didn't respond after 10 seconds.");
}, 5000);
console.log('DUDE.01');
uiGmapGoogleMapApi.then(function(maps) {
console.log('DUDE.02');
$timeout.cancel(uiGmapGoogleMapApiTimer);
geocoder = new google.maps.Geocoder();
resolve(geocoder);
}, function(err) {
console.log('DUDE.03');
});
So, when I'm offline, the timer will kick in, and I send the user back to the login page. (Originally I simply exit the app. It works in android, but in iOS it doesnt work, it's in fact forbidden by Apple).
So... that's why now I'm sending it back to login page.
Now, in the login page, I reactivate my wifi.... and once I'm back in the page that (is supposed to) show the map.... it breaks. The success handler of uiGmapGoogleMapApi.then never gets called. (Dude.01 gets printed, but Dude.02 nor Dude.03 get printed).
So... that page (wrongly) thinks that the device is still disconnected.
I suppose it's because the loading of google map javascripts is only done once (during load -- that´s why if I close my app, and return back, things will run just fine).
So... it's not really lazy loading (?). Or... if it's lazy loading, it doesn't seem to support scenarios like... try loading it the second time (if the first time failed because of connectivity).
Is anyone familiar enough with the source code of angular-ui.github.io/angular-google-maps/ to suggest what's the solution for this problem?
I looked at the logs I put in the library's code... I came to the conclusion: I need way to get line 183 to be re-executed on the second time I call uiGmapGoogleMapApi.then ... Currently it doesn't. It only gets called the first, when I start my app, and having internet connection since the beginning.
And based on what I understand from this doc on "provider", I need the uiGmapGoogleMapApi to be reinstantiated (right before) the second time I try to use it.
https://docs.angularjs.org/api/auto/service/$provide
Is that right? How?
Looks like I'm battling against provider caching here. Because I use dependency injection in my controller to get reference to uiGmapGoogleMapApi. (I have .controller('myctrl', function(uiGmapGoogleMapApi) {...})
what I might need is:
.controller('myctrl', function() {
var uiGmapGoogleMapApi = $injector.get('uiGmapGoogleMapApi');
//or something along that line maybe
})
I just tried it, still doesn't work.
Please help.
Thanks,
Raka
Well, my "solution" is: instead of going to login page, I simply refresh the app., by setting the current url of the window object to index.html.

Non-angular page opened with click - angular not defined using ignoreSynchronization or waiting for Angular without

After a lot of research, and tinkering, I can't seem to actually get my Protractor test to do anything else other than have an Angular related error, even though I am using browser to avoid Angular being detected at all.
The test involves an Angular app, opening a dropdown in it, and clicking on the link for the console; the console opens a non-Angular admin page in a separate window.
So based on the many informative SO posts I found, I first used this...
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
//expect for new window here
});
});
Which appeared to work, as I could get to the window through repl pretty easily.
The issue is when either of the following were added...
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
});
});
One expect check the URL and the other checks for the header element on the page, which is a table header. When I run this, I get the following:
Error while waiting for Protractor to sync with the page: "angular could not be found on the window"
When I decide to use browser.ignoreSynchronization = true, both in the function, or in a beforeEach, with or without a following afterEach setting it to false, I get the following:
JavascriptError: angular is not defined
I can't seem to get any "useful" errors to help me debug it, and trying it in repl does not help, as I get the same issue.
To be comprehensive, trying my URL expect without getting the second window will give me the root, and the other will fail.
Just doing one or the other will cause the same problem.
Changing to regular syntax (element(by.css...)) does not change things.
So much for my first question...
It appears that my use of browser.getLocationAbsUrl() is meant to be used for an Angular page, and was causing my issue...
Essentially, even though I believed I was using pure Webdriver calls, that call still required Angular on the page to work...
As stated in another post, the use of browser.driver.getCurrentUrl() is a non-Angular call using Webdriver, and fixed the problem. Thus, the final code is the following...
browser.sleep(1000); //to wait for the page to load
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
expect(browser.driver.getCurrentUrl()).toContain('/console/login.jsp');
expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
});
});
This works without setting ignoreSynchronization, BTW.
I realized it would probably be something relatively simple to fix it, just didn't expect I'd get it that quickly (I intended on submitting the question last night, but posted it this morning instead).
In any case, I hope this will at least be a good reference for anyone else facing the same issue.
Seems like getLocationAbsUrl is angular abs url.
Try using the native driver getCurrentUrl instead.
-- expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
++ expect(browser.driver.getCurrentUrl() ...

Protractor timeouts

I've been developing automated tests in Protractor for quite some time and like many of you, I've run into gaps which can only be crossed with the browser.sleep()-bridge. I'm not a fan of hard coding things such as this but if it's a necessity I will.
The tests I've developed have brought me to a point where every browser.sleep(1000) has a major impact on my runtime. The tests are currently testing permissions for different accounts (128 exactly) and this involves logging in and out whilst checking what every account has and has not received access to.
The website I'm testing is a pure AngularJS application which, in my eyes, should make browser.sleep() a deprecated method since there is a browser.waitForAngular() method that accurately waits until the page is fully loaded compared to browser.sleep() which waits a set amount of time and if your website isn't loaded within that time (it happens), you'll have an inconsistent test (nobody likes inconsistency).
Research has led me to believe that browser.waitForAngular() does not take into account animations and related time-consuming features since they're not AngularJS related yet this is not implemented in our website. Also waitForAngular() basically waits for $digest, $http, and $timeout.
What I'm asking is wether this is something which is regarded as an acceptable loss since Protractor is great in general or is there something I'm overlooking here?
TL;DR:
Are there solutions out there to allow us not to settle for browser.sleep()?
Sources: Protractor Timeout Docs,
Timeout-spec.js (protractor docs),
Issue909, Issue279, Issue92, StackQuestion1
If you can devise some sort of test to determine if whatever you're waiting for has completed, you can use browser.wait. Taking ideas from from http://docsplendid.com/archives/209, you can pass a function that returns a promise that resolves to true or false, such as one that uses isPresent
browser.wait(function() {
return element(by.id('some-element')).isPresent();
}, 1000);
or if you have some more complicated condition you can use promise chaining:
browser.wait(function() {
return element(by.id('some-element')).isPresent().then(function(isPresent) {
return !isPresent;
});
}, 1000);
and the command flow will wait, repeatedly calling the function passed to wait, until the promise it returns resolves to true.
This is the way if you want to perform any action when element present or want to wait until it present on page.
element(by.id).isPresent().then(function(result) {
if (result) {
nextButton.click();
}
else{
browser.wait(function () {
return browser.isElementPresent(element(by.id));
},50000);
}
}).then(function () {
nextButton.click();
});
},

How to implement callback in ngHistory in Pubnub?

When trying to retrieve the history message in the on event , the loading time is too long.
The spinner show and hides too fast. But the message is not yet loaded.
How can we calculate or get the exact time to make the history load?
$scope.limit = 100
PubNub.ngHistory( {
channel : $scope.channel,
limit : $scope.limit
});
$rootScope.$on(PubNub.ngMsgEv($scope.channel), function(ngEvent, payload) {
**ActivityIndicator.showSpinner();**
$scope.$apply(function(){
$scope.messages.push(payload.message);
});
$(".messages-wrap").scrollTop($(".messages-wrap")[0].scrollHeight);
**ActivityIndicator.hideSpinner();**
});
Thank you so much for trying out the PubNub AngularJS API! I'll try
to provide some help. There is a little bit of a difference between
the PubNub JS API and the PubNub AngularJS API in this case.
Background
Behind the scenes, The PubNub JS API history() method returns instantly,
and invokes the callback when the given "page" of history is retrieved.
The AngularJS API, in its quest for simplifying this interaction, does not
take a callback - instead, it calls $rootScope.$broadcast() for each message
in the returned history payload.
In this version of the AngularJS API, it's not currently possible to "get inside"
the 'ngHistory' method to provide a callback. However, there are 2 solutions
available to you: one has always been there, and the second one I just added
based on your feedback.
Solutions
1) See codepen here (http://codepen.io/sunnygleason/pen/afqmh). There is an "escape hatch" in the PubNub AngularJS API that lets you call the JS API directly for advanced use cases, called jsapi. You can call PubNub.jsapi.history({channel:theChannel,limit:theLimit,callback:theCallback}). The only thing to keep in mind is that this will not fire message events into the $rootScope, and you will need to call $rootScope.$apply() or $scope.$apply() to make sure any changes you make to $scope within the callback function are propagated properly to the view.
2) See codepen here (http://codepen.io/sunnygleason/pen/JIsek). If you prefer a promise-based approach, I just added an ngHistoryQ() function to version 1.2.0-beta.4 of the PubNub AngularJS API. This will let you write code like:
PubNub.ngHistoryQ({channel:theChannel,limit:theLimit}).then(function(payload) {
payload[0].forEach(function(message) {
$scope.messages.push(message);
}
});
You can install the latest version of the AngularJS SDK using 'bower install pubnub-angular'.
With either of these solutions, you should be able to display and hide your spinner
accordingly. The only difference is in #2, you'll want to write code like this:
var historyPromise = PubNub.ngHistoryQ({channel:theChannel,limit:theLimit});
showSpinner();
historyPromise.then(function(payload) {
// process messages from payload[0] array
hideSpinner();
});
Does this help? Let me know what you think. Thank you again so much for trying this out.
Can you programmatically turn the spinner on at history call time, and programmatically disable it at callback time?

AngularJS $http.post responses activated much faster if periodic $rootScope.$digest in effect

In our very large and quite complex AngularJS application, I noticed (by accident!) that a line like this in my main module setup...
application.run(function($rootScope) {
window.setInterval( () => { $rootScope.$digest(); }, 1000);
});
...has significant positive impact, in the activation time of our $http.post requests.
A small part of our code that deterministically reproduces the behaviour is this:
// In the partial
<button ... ng-click="buttonHandler" ...>
// In the controller
$scope.buttonHandler = function() {
$http.post(....).success( function() { console.log("Activated"); })
}
We associate a button's ng-click handler with invocation of one of our web services.
The web service itself responds within 30ms (according to Chrome developer tools).
However, the code inside the .success handler is executed after 1.75 - 2.3 seconds (and only then is the message "Activated" displayed in the console).
However, when we put the Eternal rootScope $digest Hack (TM) in place, the activation occurs in less than a second! :-)
I can only guess that the rootScope $digest somehow 'triggers' the actual invocation of the .success handler, and since the webservice itself responds in 30ms, the activation time depends on when the button press happens to fall in the 1 second period of the hack's setInterval.
I am not saying that this is a recommended practise - but i was very surprised to see it happen. Note that there are no console errors logged or any other mischief reported anywhere in my assertive checks - the code works fine with or without the hack, but with significantly improved performance when the hack is in place.
Any idea what is going on?
Promises in Angular queue up a callback with $rootScope.$evalAsync(callback).
The callback checks to see whether the promise has been resolved/rejected.
$evalAsync schedules the task to run after the next digest cycle is complete.
Therefore, if you're preemptively asking for a digest cycle, your promise may be resolved quicker.
Source: https://github.com/angular/angular.js/blob/master/src/ng/q.js#L175

Resources