I am having issue when i try to logout and perform a location.path('/') to homepage.
Below is my code,
angular.module('MyApp')
.controller('LogoutCtrl', function($location, $auth,$rootScope) {
if (!$auth.isAuthenticated()) { return; }
$auth.logout()
.then(function() {
$auth.logout();
$rootScope.user='';
$location.path('/');
});
});
my app.js for this calling is :
.state('login.logout', {
url: '/logout',
template: null,
controller: 'LogoutCtrl'
})
I found that it is not redirecting when I perform the logout action in the same state. Which is http://localhost:8000/#/
But it will work when I'm in different state. Any guidance pls?
1.your using state provider, so whenever you want to redirect page using url need to use like
$location.url('/');
if you want to use path then u need to pass state name as parameter for $location
$location.path('/page/login');
here '/page/login' is your login or whatever page you want to redirect that page state.
I highly recommend you use ui-router for your redirects as well.
Have a 'home' state point to the '/' url
.state('Home', {
url: '/',
....
})
and then just do something like
$auth.logout()
.then(function() {
// do your cleanup
return $state.go('Home');
})
Try:
window.location.href = "/";
Related
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.
Just started using angular and I'm trying to learn as fast as I can. I'm relatively new to SPA's so please bear with me and feel free to tell me if what I want to do is not feasible. What I'm currently stuck on now, is how do I protect my routes when using the ui-router?
What do I want to do?
There are routes that I don't want non-logged in users to access.
For example, /home and /login are okay for anonymous users.
/dashboard should only be for those that are logged in.
I want it so if a user tries to access /dashboard in the future without being logged in, they are not able to.
What have I already tried?
I have tried using the angular-permission module found here: https://github.com/Narzerus/angular-permission
The problem is..I'm not quite sure how to use it (nor if I'm using it properly).
What is currently happening?
In my login controller, once a user submits their username and password it makes a /POST to my web-sever. Once it gets the result, (regardless of what it is for the moment) I've got it redirecting to /dashboard.
Right now nothing should be getting to the /dashboard because no permissions have been set, yet I am (incorrectly) allowed to see the dashboard. I can both (1) successfully be redirected to the dashboard without permission and (2) access /dashboard without permission.
What does my code look like right now?
controllers.js
var controllers = angular.module('controllers',[])
// Login Controller -- This handles the login page that the user can enter
// enter his username & password.
controllers.controller('loginController', function($scope, $state,$location, LoginService){
$scope.email = "";
$scope.password = ""
$scope.login = function(){
var data = ({email:"test", password: "ayylmao"})
LoginService.login(data).then(function(res){
console.log(res);
})
.catch(function(err){
console.log("ERROR!");
console.log(err);
$state.go('dashboard')
})
}
})
app.js
//Definition: The parent module
var myApp = angular.module('clipboardApp', ['services','controllers', 'permission','ui.router']);
//Code below taken from the angular-permission docs.
angular
.module('fooModule', ['permission', 'user'])
.run(function (PermissionStore, User) {
// Define anonymous permission)
PermissionStore
.definePermission('anonymous', function (stateParams) {
// If the returned value is *truthy* then the user has the permission, otherwise they don't.
//True indicates anonymous.
//Always returning true to indicate that it's anonymous
return true;
});
});
//This will be serving as the router.
myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
//By default go
$urlRouterProvider.otherwise('/home');
//Views are
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'loginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'views/dashboard.html',
controller: 'dashboardController',
data: {
permissions: {
except: ['anonymous'],
redirectTo: 'login'
}
}
});
});
Here is a working example with secured routes. In this example any state start with app. will go via the auth interceptor. $transitions.onBefore hook can be use as follows to satisfy your requirement.
.run(($transitions, $state, $injector) => {
$transitions.onBefore({
to: 'app.**'
}, () => {
const $window = $injector.get('$window');
if (!$window.sessionStorage.getItem('user')) {
return $state.target('login', $state.transition.params());
}
return true
});
});
https://plnkr.co/edit/ZCN2hB34mMEmBJulyaAJ?p=info
it's probably a rookie mistake but I am having trouble changing my page using:
$state.go('login');
My routing looks as following:
$stateProvider
.state('login', {
url: "/login",
templateUrl: "./auth/login.html",
controller: 'loginCtrl'
})
I also added a
$rootScope.$on("$stateChangeStart", function (event, next) {...}
just to check if it gets there after I use $state.go() and yes; it gets there but it does not change my page or URL at all. Changing the page works fine with ui-sref="login" inside a view.html.
Other syntaxes I tried:
$state.go('login', null, {options: { location : true } } );
$state.go('login', {}, {location : true});
Btw, what I am trying to accomplish is redirecting to a login-page when the user is not authorized inside the $stageChangeStart-event.
Any ideas?
Visit Angular ui router - Redirection doesn't work at all . It gave me a more clear idea of what I was doing wrong.
The actual solution for me was found at the following page answered by frankwallis:
https://github.com/angular-ui/ui-router/issues/600
I replaced my default $urlRouterProvider.otherwise('/yourpage'); with
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("app.home");
});
Too bad I don't really understand the solution but atleast it works now!
Anyone tried to change view via $location.path with ui-route, but with a parameter?
I'm trying to do that but it doesn't work. I think it's from my app.js routes definition that doesn't work
What I want is when I change to 'show-instance' (always with an id), I'm redirected to editing-instance.html.
controller.js
.saveShow($scope.spectacle)
.then(function (data) {
if ($scope.spectacle.ShowId === null) {
$location.path('show-instance/' + data);
}
else {
$location.path('listing-shows');
}
})
And in my app.js
$stateProvider.state('show-instance', {
url: '/show/instance/:eventId',
templateUrl: 'show/editing-instance/editing-instance.html'
});
Thanks for any help.
Instead of using $location, use the $state provider that comes with UI Router:
$state.go("show-instance", {
eventId: "123"
});
$state.go is the optimum approach while using ui.router. However if you need to use $location, then do not use the state name to transition. Use url instead.
$location.path('/show/instance/data')
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);
}]
}
})