AngularJS Resolve a route based on a service promise -
i using ngroute , and trying routes resolve based on result of function in service have defined
my service follows:
app.factory('authservice', function ($q,$location,$http) { var isloggedin = false; return { hasloginsession: function(){ var defer = $q.defer(); if(isloggedin) { //user has valid session previous getsession.json request defer.resolve(isloggedin); } else { return $http.get('/session/getsession.json').success(function(data, status, headers, config) { isloggedin = data.success; if(isloggedin) { defer.resolve(isloggedin); } else { defer.reject("ex_login_session_is_unknown"); } }). error(function(data, status, headers, config) { isloggedin=false; defer.reject("ex_login_session_is_unknown"); }); } return defer.promise; } }; });
so can see have simple session check function sets property based on result of http request.
i have routing setup so, resolve on route path testing @ moment:
var app = angular.module('pinpointersapp', ['ngroute']); app.config( function($routeprovider,$httpprovider) { //$httpprovider.interceptors.push(interceptor); $routeprovider. when('/login', { templateurl: 'login.html', controller: 'logincontroller' }). when('/map', { templateurl: 'partials/map.html', controller: 'mapcontroller' }). when('/locations', { templateurl: 'partials/locations.html', controller: 'locationscontroller' }). when('/', { templateurl: 'partials/locations.html', controller: 'locationscontroller', resolve: { checksession: function ($q,authservice) { //var defer = $q.defer(); //defer.reject("ex_login_session_is_unknown"); //return defer.promise; return authservice.hasloginsession(); } } }); }); app.run(['$rootscope', 'authservice', function ($rootscope, authservice) { $rootscope.$on("$routechangeerror", function (event, current, previous, error) { console.log(error); //perform other stuff here, e.g. redirect login view }); }]);
the server side request being made, , seeing pause in view loading until response received. in test returning fail case , reject state of promise in order cause $routechangeerror fired, never , view continues load.
if use commented out lines of test code in resolve block instead of service routine call, so
resolve: { checksession: function ($q,authservice) { var defer = $q.defer(); defer.reject("ex_login_session_is_unknown"); return defer.promise; //return authservice.hasloginsession(); } }
then routechangeerror event fired, missing in order use result of service routine call?
ok, figured out did wrong, in service had 1 many return statements, needed remove return keyword before opening $http request , works required.
Comments
Post a Comment