$locationChangeStart is not working in firefox - angularjs

$scope.$on("$locationChangeStart", function (event, next, current) {
if (!$rootScope.isPopupOpen) {
if ($rootScope.isUrlLoad) {
window.location.reload();
}
}
$rootScope.isUrlLoad = true;
});
In other browser,i have no problem for loading..But in firefox it continuously loading.can anyone please suggest me?

Your problem it's probably related to the fact $locationChangeStart it's called even the first time your page load.
Simply get rid of this issue with a flag:
var firstTime = true;
$scope.$on("$locationChangeStart", function (event, next, current) {
if(firstTime){
firstTime = false;
event.preventDefault();
return;
}
if (!$rootScope.isPopupOpen) {
if ($rootScope.isUrlLoad) {
window.location.reload();
}
}
$rootScope.isUrlLoad = true;
});

Related

Execute an Angular function only if the current tab is active in the browser

I have an angular js function which should be called for every 2 seconds only when the current tab is open in the browser. Is there any way to check whether the current page is active in the browser.
$scope.callAtInterval = function() {
var url = "http://127.0.0.1/test";
$http.get(url).success( function(response) {
$scope.initial = response;
},
function errorCallback(response) {
$scope.result=response;
});
}
$interval( function(){ $scope.callAtInterval(); }, 5000);
}
I think below piece of code is self-explanatory
import { HostListener} from "#angular/core";
#HostListener("window:visibilitychange", ["$event"])
onVisibilityChange($event) {
const isVisible = $event.target.visibilityState === 'visible';
this.logger.info(isVisible);
if (isVisible) {
// tab is visible
} else {
// tab is not-visible
}
}
You would use the focus and blur events of the window:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// cancel your interval function
break;
case "focus":
// emit your interval function
break;
}
}
$(this).data("prevType", e.type);
})

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

Angular infinite digest loop with ui-router

The problem I was initially trying to solve was to redirect a user to the login page if they are not logged in and vice versa.
I did this with the following code
.run(function($rootScope, $http, AppService, $state) {
$rootScope.$on('application:refreshtoken', function(rootScope, token) {
if(token) {
$http.defaults.headers.common['X-Auth-Token'] = token;
AppService.setAuthToken(token);
AppService.resetLoginTimeout();
}
});
$rootScope.$on('$stateChangeSuccess', function() {
$http.get('/api/heartbeat');
});
// This is the really pertinent bit...
$rootScope.$on('$stateChangeStart', function(e, toState) {
if(toState.name === 'login') {
if(AppService.getIsLoggedIn()) {
e.preventDefault();
$state.go(AppService.getRedirectPage());
}
} else {
if(!AppService.getIsLoggedIn()) {
e.preventDefault();
$state.go('login');
}
}
});
});
AppService
.factory('AppService', ['$rootScope', 'locker', '$http', '$state',
function ($rootScope, locker, $http, $state) {
var _isLoggedIn = locker.get('loggedIn', false),
_authToken = locker.get('authtoken', null),
_roles = locker.get('roles', null),
_permissions = locker.get('permissions', null),
_user = locker.get('user', null),
_userid = locker.get('userid', null),
_userprefs = locker.get('userprefs', null),
_timedout,
_timeoutId,
service = {};
if (_authToken) {
$http.defaults.headers.common['X-Auth-Token'] = _authToken;
}
service.setIsLoggedIn = function (isLoggedIn) {
_isLoggedIn = isLoggedIn;
this.doLogin();
broadcastLogin();
};
service.doLogin = function () {
if (_isLoggedIn) {
locker.put({
loggedIn: _isLoggedIn,
authtoken: _authToken,
roles: _roles,
permissions: _permissions,
user: _user,
userprefs: _userprefs
});
}
};
service.doLogout = function (cb) {
_isLoggedIn = false;
_authToken = null;
_roles = null;
_permissions = null;
_user = null;
_userid = null;
_userprefs = null;
delete $http.defaults.headers.common['X-Auth-Token'];
locker.clean();
cb();
};
service.getIsLoggedIn = function () {
return _isLoggedIn;
};
service.setAuthToken = function (authToken) {
_authToken = authToken;
locker.put({
authtoken: _authToken
});
};
service.getAuthToken = function () {
return _authToken;
};
service.setUserid = function (userid) {
locker.put('userid', userid);
_userid = userid;
};
service.getUserid = function () {
return _userid;
};
service.setUser = function (user) {
_user = user;
};
service.getUser = function () {
return _user;
};
service.setRoles = function (roles) {
_roles = roles;
};
service.getRoles = function () {
return _roles;
};
service.setPermissions = function (permissions) {
_permissions = permissions;
};
service.getPermissions = function () {
return _permissions;
};
service.setUserPreferences = function (prefs) {
_userprefs = prefs;
};
service.getUserPreferences = function () {
return _userprefs;
};
service.resetLoginTimeout = function () {
if (_timeoutId) {
clearTimeout(_timeoutId);
}
_timeoutId = setTimeout(function () {
$rootScope.$broadcast('application:logintimeoutwarn');
}, 1000 * 60 * 4);
};
service.setTimedOut = function (timedout) {
_timedout = timedout;
};
service.getTimedOut = function () {
return _timedout;
};
service.extendSession = function () {
$http.get('/api/heartbeat');
};
service.goDefaultUserPage = function () {
var success = false;
if (_userprefs.landingPage) {
$state.go(_userprefs.landingPage);
success = true;
} else {
var permissionRoutes = {
'regimens': 'regimens.do',
'pathways': 'pathways',
'manage.users': 'manageusers.do',
'manage.practices': 'managepractices.do',
'patients': 'patients'
};
_.some(_permissions, function (el) {
var state = $state.get(permissionRoutes[el]);
if (!state.abstract) {
$state.go(state.name);
success = true;
return true;
}
});
}
return success;
};
service.getRedirectPage = function () {
var page = false;
if (_userprefs.landingPage) {
page = _userprefs.landingPage;
} else {
var permissionRoutes = {
'regimens': 'regimens.do',
'pathways': 'pathways',
'manage.users': 'manageusers.do',
'manage.practices': 'managepractices.do',
'patients': 'patients'
};
_.some(_permissions, function (el) {
var state = $state.get(permissionRoutes[el]);
if (!state.abstract) {
page = state.name;
return true;
}
});
}
return page;
};
function broadcastLogin() {
$rootScope.$broadcast('application:loggedinstatus');
}
broadcastLogin();
return service;
}
])
This code works great until I take a very specific set of actions:
Login
Close the open tab or window
Open a new tab and go to the application
Since I am still logged in to the application, I have a user object and a valid token, but I am getting error:infdig Infinite $digest Loop. It eventually resolves and goes to the correct state, but it takes a while and the path flickers (I can post a video if needed).
I tried using $location.path instead of $state.go in the $rootScope.$on('$stateChangeSuccess') callback, but the issue persists.
This doesn't really affect the functioning of the application, but it is annoying. I also don't really want to change my locker storage to session storage because I want the user to stay logged in if they close the tab and reopen.
I would say, that the issue is hidden in the improper if statements inside of the $rootScope.$on('$stateChangeStart'... Check this:
Ui-Router $state.go inside $on('$stateChangeStart') is cauzing an infinite loop
With a general suggestion:
let's redirect ($state.go()) only if needed - else get out of the event listener
$rootScope.$on('$stateChangeStart' ...
if (toState.name === 'login' ){
// going to login ... do not solve it at all
return;
}
Second check should be: is user authenticated (and NOT going to login)?
if(AppService.getIsLoggedIn()) {
// do not redirect, let him go... he is AUTHENTICATED
return;
}
Now we have state, which is not login, user is not authenticated, we can clearly call:
// this is a must - stop current flow
e.preventDefault();
$state.go('login'); // go to login
And all will work as we'd expected
Very detailed explanation and working example could be also found here...
this usally happens when the app gets stuck between a route rejection through a resolve clause and an automatic redirection on the previous route where the landing page will redirect to some page, say auth, and the auth page needs some conditions to let you in and if it fails or it will redirect back to some other page, hence the cycle, make sure you get your story straight and if needed use an intermediate state to clear all preferences and take the default path

Registering beforeunload event in directive

I have the following directive which I use to warn the user if they attempt to close the window or navigate away without saving their changes:
app.directive('dirtyTracking', ['$window', function ($window) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = getProperty($scope, $element.attr('name'));
return formObj && formObj.$pristine === false;
}
//So we can read string keys such as foo.bar and correctly
//traverse the javascript object
function getProperty(obj, prop) {
var parts = prop.split('.'),
last = parts.pop(),
l = parts.length,
i = 1,
current = parts[0];
while ((obj = obj[current]) && i < l) {
current = parts[i];
i++;
}
if (obj) {
return obj[last];
}
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes.';
}
}
window.onbeforeunload = areYouSurePrompt;
//window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
As it currently stands, this works, but as you can see, I have to explictly set the window.onbeforeunload property. The problem with this approach is that if I have other directives that want to do things on the save event, they will clobber each other.
When I attempted to use window.addEventListener or $window.addEventListener the event does not seem to work as expected.
Stepping through the debugger, the code does enter the areYouSurePrompt function and does return the string, however I am not prompted with a confirm dialog before the window closes.
I am aware I can use the approach where I save the current value of window.onbeforeunload but I'd rather figure out why using the addEventListner isn't working as expected.

Detect when user leaves window

I want to detect when user exit window with AngularJS. My app doesn't use ngRoute. So, I can't use $destroy or $locationChangeStart.
Can you help me ?
You can use $locationChangeStart:
$scope.$on('$locationChangeStart', function( event ) {
var answer = confirm("Are you sure you want to leave this page?")
if (!answer) {
event.preventDefault();
}
});
Or use onbeforeunload:
window.onbeforeunload = function (event) {
var message = 'Are you sure you want to leave this page?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}

Resources