Cancel route and redirect to other route without displaying the original content in AngularJS -
i want check http services see if user authenticated , if has permission see page (controller) in angularjs 1.2.0rc1.
i have scenario: user wants visit http://www.example.com/content. content should not accessible when or not authenticated. if user not authenticated, should redirected http://www.example.com/login.
now managed this, see rendered html of content page briefly. don't want this. how redirect login page, without rendering content page?
i register routes such:
$routeprovider.when('/login', route.resolve('login', false)) $routeprovider.when('/content', route.resolve('content', true))
now i've tried this:
$rootscope.$on('$routechangestart', function (event, route) { if (route.requireslogin) { $http.get('/api/user/loggedin/').then(function (response) { if (response !== 'true') { $location.path('/login'); } }); } });
which works, still see content of html of other page (content) flashing.
i've read here can try change resolve functionality when route resolved:
var resolve = function (basename, requireslogin) { var routedef = {}; var dependencies = [routeconfig.getcontrollersdirectory() + basename + 'controller.js']; routedef.templateurl = routeconfig.getviewsdirectory() + basename.tolowercase() + '.html'; routedef.controller = basename + 'controller'; routedef.requireslogin = requireslogin; routedef.resolve = { load: ['$q', '$rootscope', '$http', '$location', function ($q, $rootscope, $http, $location) { console.log(requireslogin); if (requireslogin) { return checkloggedin($q, $rootscope, $http, $location); } else { return resolvedependencies($q, $rootscope, dependencies); } }] }; return routedef; }
but here page displayed briefly.
hope can me out.
the first answer should work, using $q use defer.resolve()
or defer.reject("rejection_reason")
listen $routechangeerror
in top-level controller bound an element outside of ng-view routeprovider manages.
so in html, like:
<body ng-app="app" ng-controller="documentctrl"> <div ng-view> </div> </body>
then route of yours defined like:
when('/home', { templateurl: templateurl blah, controller: basename + 'controller', resolve: { load: function($q, my_user_service){ var defer = $q.defer(); if(~my user logged_in logic returns true~){ defer.resolve(); } else { defer.reject("not_logged_in"); } return defer.promise; } } }).
then documentctrl controller contain:
$scope.$on("$routechangeerror", function(evt,current,previous,rejection){ if(rejection == "not_logged_in"){ //do } else { //or else } });
i'm running above , there's no flash of views shouldn't loaded.
Comments
Post a Comment