Como faço para cancelar o evento de mudança de rota no AngularJs?
Meu código atual é
$rootScope.$on("$routeChangeStart", function (event, next, current) { // do some validation checks if(validation checks fails){ console.log("validation failed"); window.history.back(); // Cancel Route Change and stay on current page } });
com isso, mesmo se a validação falhar, o Angular puxará o próximo modelo e os dados associados e, em seguida, voltará imediatamente para a vista / rota anterior. Eu não quero angular para puxar o próximo modelo e dados se a validação falhar, idealmente não deve haver window.history.back (). Eu até tentei event.preventDefault (), mas não uso.
Em vez de $routeChangeStart
use $locationChangeStart
Aqui está a discussão sobre o assunto: https://github.com/angular/angular.js/issues/2109
Editar 06/03/2018 Você pode encontrá-lo nos documentos: https://docs.angularjs.org/api/ng/service/$location#event-$locationChangeStart
Exemplo:
$scope.$on('$locationChangeStart', function(event, next, current) { if ($scope.form.$invalid) { event.preventDefault(); } });
$locationChangeStart
// assuming you have a module called app, with a angular.module('app') .controller( 'MyRootController', function($scope, $location, $rootScope, $log) { // your controller initialization here ... $rootScope.$on("$locationChangeStart", function(event, next, current) { $log.info("location changing to:" + next); }); } );
Eu não estou completamente feliz em ligar isso no meu controlador de raiz (controlador de nível superior). Se houver um padrão melhor, eu adoraria saber. Eu sou novo no angular 🙂
Uma solução é transmitir um evento ‘notAuthorized’ e capturá-lo no escopo principal para alterar novamente o local. Eu acho que não é a melhor solução, mas funcionou para mim:
myApp.run(['$rootScope', 'LoginService', function ($rootScope, LoginService) { $rootScope.$on('$routeChangeStart', function (event, next, current) { var authorizedRoles = next.data ? next.data.authorizedRoles : null; if (LoginService.isAuthenticated()) { if (!LoginService.isAuthorized(authorizedRoles)) { $rootScope.$broadcast('notAuthorized'); } } }); } ]);
e no meu controlador principal:
$scope.$on('notAuthorized', function(){ $location.path('/forbidden'); });
Nota: há alguma discussão sobre este problema no site angular, ainda não resolvido: https://github.com/angular/angular.js/pull/4192
EDITAR:
Para responder ao comentário, aqui estão mais informações sobre os trabalhos do LoginService. Contém 3 funções:
(*) Minha session é preenchida quando a rota muda. Eu substituí o método when () para preencher a session quando vazia.
Aqui está o código:
services.factory('LoginService', ['$http', 'Session', '$q', function($http, Session, $q){ return { login: function () { var defer = $q.defer(); $http({method: 'GET', url: restBaseUrl + '/currentUser'}) .success(function (data) { defer.resolve(data); }); return defer.promise; }, isAuthenticated: function () { return !!Session.userLogin; }, isAuthorized: function (authorizedRoles) { if (!angular.isArray(authorizedRoles)) { authorizedRoles = [authorizedRoles]; } return (this.isAuthenticated() && authorizedRoles.indexOf(Session.userRole) !== -1); } }; }]); myApp.service('Session', ['$rootScope', this.create = function (userId,userLogin, userRole, userMail, userName, userLastName, userLanguage) { //User info this.userId = userId; this.userLogin = userLogin; this.userRole = userRole; this.userMail = userMail; this.userName = userName; this.userLastName = userLastName; this.userLanguage = userLanguage; }; this.destroy = function () { this.userId = null; this.userLogin = null; this.userRole = null; this.userMail = null; this.userName = null; this.userLastName = null; this.userLanguage = null; sessionStorage.clear(); }; return this; }]); myApp.config(['$routeProvider', 'USER_ROLES', function ($routeProvider, USER_ROLES) { $routeProvider.accessWhen = function (path, route) { if (route.resolve == null) { route.resolve = { user: ['LoginService','Session',function (LoginService, Session) { if (!LoginService.isAuthenticated()) return LoginService.login().then(function (data) { Session.create(data.id, data.login, data.role, data.email, data.firstName, data.lastName, data.language); return data; }); }] } } else { for (key in route.resolve) { var func = route.resolve[key]; route.resolve[key] = ['LoginService','Session','$injector',function (LoginService, Session, $injector) { if (!LoginService.isAuthenticated()) return LoginService.login().then(function (data) { Session.create(data.id, data.login, data.role, data.email, data.firstName, data.lastName, data.language); return func(Session, $injector); }); else return func(Session, $injector); }]; } } return $routeProvider.when(path, route); }; //use accessWhen instead of when $routeProvider. accessWhen('/home', { templateUrl: 'partials/dashboard.html', controller: 'DashboardCtrl', data: {authorizedRoles: [USER_ROLES.superAdmin, USER_ROLES.admin, USER_ROLES.system, USER_ROLES.user]}, resolve: {nextEvents: function (Session, $injector) { $http = $injector.get('$http'); return $http.get(actionBaseUrl + '/devices/nextEvents', { params: { userId: Session.userId, batch: {rows: 5, page: 1} }, isArray: true}).then(function success(response) { return response.data; }); } } }) ... .otherwise({ redirectTo: '/home' }); }]);
Para alguém que tropeça sobre isso é uma pergunta antiga, (pelo menos em 1.4 angular) você pode fazer isso:
.run(function($rootScope, authenticationService) { $rootScope.$on('$routeChangeStart', function (event, next) { if (next.require == undefined) return var require = next.require var authorized = authenticationService.satisfy(require); if (!authorized) { $rootScope.error = "Not authorized!" event.preventDefault() } }) })
Esta é a minha solução e funciona para mim, mas eu não sei se estou no caminho certo porque eu sou novo em tecnologias web.
var app = angular.module("app", ['ngRoute', 'ngCookies']); app.run(function($rootScope, $location, $cookieStore){ $rootScope.$on('$routeChangeStart', function(event, route){ if (route.mustBeLoggedOn && angular.isUndefined($cookieStore.get("user"))) { // reload the login route jError( 'You must be logged on to visit this page', { autoHide : true, TimeShown : 3000, HorizontalPosition : 'right', VerticalPosition : 'top', onCompleted : function(){ window.location = '#/signIn'; window.setTimeout(function(){ }, 3000) } }); } }); }); app.config(function($routeProvider){ $routeProvider .when("/signIn",{ controller: "SignInController", templateUrl: "partials/signIn.html", mustBeLoggedOn: false });
Caso você precise impedir que a rota altere o evento $routeChangeStart
(ou seja, se você deseja executar alguma operação com base na próxima rota ), injete $route
e dentro da chamada $routeChangeStart
:
$route.reload()
Eu encontrei este relevante
var myApp = angular.module('myApp', []); myApp.run(function($rootScope) { $rootScope.$on("$locationChangeStart", function(event, next, current) { // handle route changes $rootScope.error = "Not authorized!" event.preventDefault() }); });
meu post pode ajudar alguém no futuro.
var app=angular .module('myapp', []) .controller('myctrl', function($rootScope) { $rootScope.$on("locationChangeStart", function(event, next, current) { if (!confirm("location changing to:" + next)) { event.preventDefault(); } }) });