Identifying changes in the route within an Angular service

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: '/'
        });

    }]);

Answer №1

Utilizing the $routeChangeStart event allows you to listen for a broadcast triggered by $routeProvider whenever the route changes. It is unnecessary to call it in multiple places, such as controllers; simply check for it.

angular.module('lmsApp')
.service('pageAuth', ['$location', function ($location) {
var canAccess = function(event,next,current){

var user = firebase.auth().currentUser;
//requireAuth is a custom route property
    if (next.$$route.requireAuth && user == null ) {

      event.preventDefault(); //prevents route change
      alert("You must be logged in to access page!");

    }
    else {
      console.log("allowed");
    }

}

$rootScope.$on('$routeChangeStart',canAccess); 
}]);  

Inject your service in the .run() section of your application to ensure automatic checking through the mentioned broadcast.

angular.module('lmsApp')
    .run(function runApp(pageAuth){
 //rest of your stuff
}); 

Answer №2

Consider implementing an event handler within the Service on $rootScope as opposed to $scope.

It is advisable to include the $routeChangeSuccess function in the ".run" section for more efficient monitoring of all pages, centralizing control rather than adding it to each controller individually.

Answer №3

To ensure proper functionality, it is recommended to utilize $rootScope instead of $scope in this scenario.

Additionally, it is advisable to invoke the listener during the initialization of the encapsulated service. Since services act as singletons, the listener will execute when injected into any controller.

angular.module('lmsApp')

.service('stateService', ['$rootScope', function ($rootScope) {
    $rootScope.$on('$locationChangeStart', (event, next, current) => {
        // handle the necessary actions here
    });

}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

How can an accordion icon be added and list toggling be accomplished when HTML data is sourced from an API instead of a JSON response?

I have an API that sends HTML data as a response. The task at hand is to add accordion icons to the items in the list and enable list toggling using HTML, CSS, JavaScript, React, and MaterialUI. Unfortunately, I am limited in my options and cannot use JQ ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...

Disable the setTimeout() function in order to prevent the countdown from refreshing

I have a JavaScript countdown function that is working well, but I am unsure how to stop and refresh the timer to extend the time. When I call the function again before it times out, it behaves strangely by showing two countdown timers because the updateTi ...

Encountering a failure when trying to run npm in a React project

I've removed the .lock file and node_modules, then reinstalled, but it's still not working. Can someone assist me with fixing this? npm ERR! gyp ERR! node -v v16.13.0 npm ERR! gyp ERR! node-gyp -v v8.2.0 npm ERR! gyp ERR! not ok npm ERR! node-pr ...

The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another: hmap.put(l,hmaps); //hmap within hmap When returning the response to the frontend, I am using the ResponseEntity meth ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

What are some ways I can utilize Babel in standalone mode to convert an HTML import into a variable declaration?

I am trying to utilize the Babel plugin babel-plugin-transform-html-import-to-string to dynamically transform my code in the browser client. However, the babel-plugin-transform-html-import-to-string is designed to run on node with file libraries, which are ...

Invert the polarity of an angular.js filtering function

Is it achievable to trigger the reverse of a filter method in HTML, such as utilizing: "item in items | filter:!AllDay" rather than "item in items | filter:AllDay" ? Or must you sustain two distinct filter methods (one for false and one for true)? ...

Combining multiple dictionaries into one single dictionary array using JavaScript

In my JavaScript code, I am working with an array that looks like this: arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}] My goal is to transform t ...

Issues with AJAX file uploads in Django

I'm encountering an issue while attempting to upload files using Ajax in Django. My approach involves utilizing FormData in Javascript. However, the problem lies on the server side. The files are expected to be received in request.FILES, but they are ...

Discovering an Improved Method for Implementing a Functional jQuery Menu Bar

Currently, I have a functioning Menubar where each button on the menu triggers a secondary Menubar using jQuery. The code snippet is as follows: <script> $(document).ready(function(){ $("#homeButton1").mouseover(function(){ $(".secondMen ...

Issues with angular ui.bootstrap functionality not functioning as expected

Having some difficulty implementing the popover element in an Angular application using ui.bootstrap. Here is a snippet of the code: In the app.js file, I include ui.bootstrap: angular.module('developerPortalApp', [ 'ui.bootstrap' ...

Utilizing THREE.js to evenly distribute particles on object surfaces, rather than on vertices

Currently, I have successfully created a particleCloud where the particles are positioned at each vertex of an imported object. However, my goal is to have the particles initially placed on the flat faces of the object instead of in between the vertices an ...

Adapting software for use with Panasonic Viera

We are in the process of transferring our current HTML/JavaScript/CSS application to the Panasonic platform. Our current setup involves using JavaScript for generating HTML and CSS for styling the application. The programming language used in the Panasoni ...

Cordova encountered an error: Execution of inline script was denied due to violation of Content Security Policy directive

As I delve into the world of Cordova and jquery mobile, I encountered a perplexing error that reads: Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: 'un ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

Having trouble accessing NWJS modules with your new windows?

When I create a window using window.open in my NWJS application, it appears that the window is unable to access any nodejs or nwjs modules. How can I find a solution for this issue? I utilize document.write to add content to the page because the content m ...