I have developed a service that checks whether a user needs to be logged in to access a particular route. Currently, the code includes the $scope.$on('routeChangeStart) function within the profileInfoCtrl.js controller, but I want to move this functionality into the service so that it can be used across multiple controllers. How should I approach this?
Existing Code:
profileInfoCtrl.js
angular.module('lmsApp', ['ngRoute'])
.controller('profileInfoCtrl', ['$scope', '$location', 'pageAuth', function($scope, $location, pageAuth){
//I want to include this in canAccess function
$scope.$on('$routeChangeStart', function(event, next) {
pageAuth.canAccess(event, next);
});
}]);
pageAuth.js
angular.module('lmsApp')
.service('pageAuth', ['$location', function ($location) {
this.canAccess = function(event, next) {
var user = firebase.auth().currentUser;
if (next.$$route.requireAuth && user == null ) {
event.preventDefault();
alert("You must be logged in to access page!");
}
else {
console.log("allowed");
}
}
}]);
routes.js
angular.module('lmsApp')
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/admin', {
templateUrl: 'view/admin.html',
css: 'style/admin.css',
controller: 'adminCtrl',
requireAuth: true
})
.otherwise({
redirectTo: '/'
});
}]);