reload page in angular js after logout - angularjs

Hi guys am a beginner in mean stack development I have tried to refresh the page after logout.I have tried location.reload(); but it doesn't work tell me the possible code for page reload in this scenario
$rootScope.$on('$routeChangeStart', function (event) {
var storage = userService.isLoggedIn();
console.log(storage);
if (!storage) {
console.log('DENY');
$rootScope.adminlogin = "adminlogin";
console.log($rootScope.adminlogin);
$location.path('/login');
$route.reload();
// $state.go('/login', null, {reload: true});
}
else {
console.log('ALLOW');
$rootScope.admindashboard = "admindashboard";
var path = $location.path();
console.log(path);
console.log(storage);
if(path == '/login'){
$location.path('/');
}
}
});

You should use $window.location.reload() from the the $window service if you want to refresh the page. It does the same thing as the reload button in your browser.
The reason you should use the $window service instead of directly accessing the native window object as per the AngularJS documentation:
While window is globally available in JavaScript, it causes
testability problems, because it is a global variable. In AngularJS we
always refer to it through the $window service, so it may be
overridden, removed or mocked for testing.
On a side note as you stated you are using the $route service, just calling $route.reload() will only reload your controllers and not your entire application.

All you need to do is this little line of Vanilia JS:
document.location.href=document.location.href
EDIT: why is this getting downvoted?

if you are using routes, then on click of Logout just route it to your login page.
Snap shot from demo:
these are my routes:
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.otherwise({ redirectTo: '/login' });
and when i click on 'Logout' on my page it should do somehting like:
<p>Logout</a></p>
it should redirect to login page as per routes.

Related

$location not redirecting to the page

I am trying to redirect to another page in my ionic app but stuck at this point. I see in console that my current path is what I want but I am not really on that page here is may code
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.views.maxCache(0);
$stateProvider.state('homepage', {
url: '/homepage',
templateUrl: 'templates/homepage.html',
controller: 'MapController'
})
.state('hotel', {
url: '/hotel',
templateUrl: 'templates/hotel.html',
controller: 'HotelController'
})
})
Controller
.controller('MapController', function($scope, $location, customservice) {
$scope.fa = function(a) {
customservice.hotel_name = {hotelName: a.innerHTML}
console.log($location.path()) // prints /homepage
$location.path('/hotel');
console.log($location.path()) // print /hotel but still on same page
}
});
The $location service allows you to change only the URL; some time it dones not reload/redirect page. Can you try $window.location.href or $state.go(), instead of $location.path(). May be it will work.
I dont know how and why but wrapping it under $timeout did the job for me
It's very confusing thing. $location only changes url without reload.
You should write like this if you want to redirect.
$window.location.href = "http://www.google.com"
Please refer Angulardoc
When should I use $location?
Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.
What does it not do?
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href
Try below:
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$window.location.href = '/hotel.html';
};
}]);

$location.path or $location.url doesn't trigger the ngRoute controller

I have a route defines as follows:
$routeProvider.
when('/projects/', {
controller: 'ProjectCtrl',
controllerAs: 'project_ctrl',
templateUrl: '/static/app/partials/project.html'
}).
After the login finishes I need the user to land on this link, hence in my controller I am using this:
vm.login = function(form) {
if (form.$valid) {
loginService.login(vm.loginFormData.username, vm.loginFormData.password);
loginService.setUpUser()
$location.url("/projects");
}
}
But unfortunately the controller associated with this view is not triggered, that is ProjectCtrl is not triggered. However when I click on the navigation link which uses in the dom, it works fine. Can someone please guide me here, may I am missing something conceptual.
Hence the larger question is how do I redirect a user in the controller using some APIs which also complies with ngRoute based controllers.
Try removing the last / in url so it matches $location.url("/projects");
$routeProvider.
when('/projects', {

Make AngularJS route accessible ONLY from application code / links

i want create a route for angularJs which will be accessible only from application code and links. The main idea is to prevent the user to access the page after directly typing route url in browser's location bar.
For route configuration i use "ngRoute" module's $routeProvider.
I can't find an answer for this question. Is the thing i need possible?
Thanks in advance.
You can listen $locationChangeStart event. In your routes you can set a parameter (I've called it "restricted" but you could call it whatever you want) like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to main page',
restricted: false
})
.when('/main', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to restricted page',
restricted: false
}).when('/restr', {
controller: 'RestrictedPageCtrl',
template: 'Allowed only from main',
restricted: '/main'
});
});
If it's false, that means there's no restriction, if it's set to a path, then the route is only accessible from that path. And you can check it with this:
app.run(function($rootScope, $location, $route) {
$rootScope.$on('$locationChangeStart', function(event, next, current) {
var nextRoute = $route.routes[$location.path()];
var currentPath = current.split('#')[1];
if (nextRoute.restricted && nextRoute.restricted !== currentPath) {
$location.path('/');
alert('You are trying to reach a restricted page!!!!');
}
});
});
You can change the behaviour and redirect user to another link or prevent location change with event.preventDefault();.
Note that if you are not using hashtag (#) in your links (html5Mode) you should change the way to get the current link.
Here's a plunker.

AngularJS + Adobe CQ5 - Browser URL does not append hash path but changes the view

I am using combination of AngularJS and Adobe CQ5.
I have implemented routing to load different views. The views are loading perfectly but the URL is not appending the #/path and it shows the base path only, e.g.
localhost:7001/cf#/content/requestpage.html#/
rather than
localhost:7001/cf#/content/requestpage.html#/checkstatus.
Due to this, when I refresh the page it loads the route path (/) template instead of loading the same view again.
I am struggling to resolve this issue. Here's my controller code:
var demoapp=angular.module('demoApp',['ngRoute','ngSanitize']);
demoapp.config(function($routeProvider,$locationProvider) {
// use the HTML5 History API
//$locationProvider.html5mode(false);
$routeProvider
.when('/', {
templateUrl: '/content/index.html?wcmmode=disabled',
controller: 'myfirstcontroller'
})
.when('/checkstatus', {
templateUrl: '/content/housetemplate.html?wcmmode=disabled',
controller: 'houseController'
})
.otherwise({
redirectTo: '/'
});
});
demoapp.controller('houseController', function($scope, $routeParams,$http)
{
//code
});
demoapp.controller('myfirstcontroller', function($scope,$http,$rootScope,$location,$compile)
{
//On Form Submit
$scope.continueForm = function(isValid){
if (isValid)
{
$location.path('/checkstatus');
}
});
});
This is not an issue with CQ5. When you open a page from Siteadmin, by default your page is loaded within contentfinder (/cf#).
Now, contentfinder already has your page URL as the hashvalue. Hence you find that the URL doesn't get updated even though your angular views work correctly.
Try accessing the same page without contentfinder. i.e.,
http://localhost:7001/content/requestpage.html
instead of
http://localhost:7001/cf#/content/requestpage.html
You should find things working as expected.

Angular - Logout redirect route

I am trying to create a route that clears the users session and redirects them back to the root homepage.
.config(function config( $routeProvider, $stateProvider ) {
$routeProvider.
when('/logout', {resolve: {redirect: function(Session){
Session.clear();
return "/home";
}}});
I'm obviously doing something wrong here, as calling
$location.path("/logout");
... ignores the function and redirects back to the default route. I've tried adding console.log statements to the function to see if it is being called.
Am I using the redirect function incorrectly?
Have you considered putting your logout logic in a separate controller? Would be a little cleaner, more robust, & make redirection more straightforward. Like so:
function LogoutController($location) {
Session.clear();
$location.path('/home');
}
The your route is:
when('/logout', {
template: '', //A template or templateUrl is required by AngularJS, even if your controller always redirects.
controller: 'LogoutController'
}).
I had the same issue and what I did instead was create a logout function in my navigationController that gets hit when the URL is clicked
<li>Log Out</li>
And in my navigationController:
$scope.logout = function () {
localStorage.clearAll();
window.location = '/logout';
};
I'm running ASP.NET behind Angular so I needed the browser (not angular) to route to /logout which is mapped in ASP.NET config (does a few other session clean ups and redirects to authentication app)
Hope this helps
just store the $sessionStorage (username) then delete the the $sessionStorage (username) ..
$scope.logout = function(){
delete $sessionStorage.sessname; //sessname is get sessionStorage username
$location.path('/login');
};
help me for this link:https://stackoverflow.com/questions/36056745/angularjs-click-logout-button-to-clear-sessionstorage-again-and-again-go-back-to
I use this approach
$routeProvider
.when('/logout', {
resolve: {
logout: ['authService', function (authService) {
authService.clear(true);
}]
}
})

Resources