AngularJS: The $routeChangeStart Event

As a newcomer to AngularJS, I'm looking for ways to determine if a user is logged in. My setup involves Sails.js on the backend and AngularJS on the frontend.

module.run(function ($location, $rootScope) {
      $rootScope.$on("$routeChangeStart", function (event, next, current) {

      });
   })

signin.js

.controller('SigninCtrl', function ($scope,$location,User,$http) {             


    $scope.signin = function(){
    var data={ email:$scope.email,password:$scope.password}
       var user=User.signin(data);
        //console.log(typeof user);
     user.success(function (data) {
                    //console.log("token signin",data);
                    var token=data.token;
                localStorage.setItem('id_token', token);
                    $location.path("/todo");
               })
               .error(function (data) {
                    //Do whatever is needed
                 //console.log(data);
               });  
        }   

  });

service :User.js signin: function(data){

            return $sails.post('/api/auth',data);
        },

Answer №1

Indeed, I have completed a rather straightforward task. For more information, you can view this plnkr.

In my implementation, userHttpService typically encapsulates $http, but since there is no actual endpoint to connect to, I am simulating a promise using the $q library.

The routeConfig provider allows for configuration of routes during setup. If utilizing something like ui router, a more elegant approach can be achieved with a settings object in the route setup. For a more advanced example, take a look at this repository.

The configuration looks as follows:

app.config(function($routeProvider, $locationProvider, routeConfigProvider) {

  $routeProvider.when('/home', { template: '<h2>Home</h2><p>Please do something</p>' })
  $routeProvider.when('/login', { controller: 'LoginController', template: '<h2>Login</h2><div><p><span>Name:</span><input type="text" ng-model="name" /></p><p><span>Password:</span><input type="password" ng-model="password" /></p></div><div><p><button type="submit" ng-click="login()">Login</button></p></div><div><p>{{error}}</p></div>' });
  $routeProvider.when('/profile', { controller: 'ProfileController', template: '<h2>Profile</h2><div><p><span>Name:</span>{{name}}</p></div>' });

  $routeProvider.otherwise('/home');

  $locationProvider.html5Mode(true);


  routeConfigProvider.addRouteWhenLoggedIn('/profile');
  routeConfigProvider.addRouteWhenLoggedIn('/home');

  routeConfigProvider.addRouteWhenLoggedOut('/home');
  routeConfigProvider.addRouteWhenLoggedOut('/login');
});

I have consolidated all templates for convenience and used the routeConfigProvider. Note that when naming it .provider('routeConfig', ..., you don't need to add Provider as Angular does it automatically.

Routes are added to different tables based on permissions for logged-in and logged-out users.

Below is the section where route navigation is handled:

app.run(function ($rootScope, routeConfig, userService) {
  $rootScope.$on('$routeChangeStart', function (e, c, p) {
    var topath = c.$$route.originalPath;

    if (userService.isLoggedIn()) {
      if (!routeConfig.isAllowedWhenLoggedIn(topath)){
        e.preventDefault();
        // Redirect using $location.path if needed
      }
    } else {
      if (!routeConfig.isAllowedWhenLoggedOut(topath)){
        e.preventDefault();
        // Redirect using $location.path if needed
      }
    }
  });
});

This process is relatively simple, involving the use of the userService to determine user login status and checking against the permission tables to decide whether navigation is allowed.

e.PreventDefault() is how navigation is prevented.

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 best way to display a list of lists in a React application?

I have a collection of lists containing data that I need to display on the view. The data: { "blocks_content": [ [ " Bakery", " Company GbR", ], [ ...

Oops! Looks like Handlebars.js is telling us that a Helper is missing

Currently, I am utilizing handlebars.js templates alongside node and express. My goal is to create a numbered list using the {{@index}} template tag. However, since the index starts at 0 and I want it to start from one, it seems that a custom helper is req ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...

What is the proper method for utilizing $http and $q in an Angular service?

I am currently working on implementing reverse geocoding to retrieve the city name from latitude and longitude data. After developing an Angular service that interacts with the Google Maps API using $http, I found myself facing challenges due to the async ...

405 (Method Not Allowed) using the concept of notion

Currently, I am heavily involved in a compact project where data submitted through a form will be seamlessly posted on Notion. An error occurred while attempting to submit the form: contact.jsx?287f:14 POST http://localhost:3000/contact 405 (Meth ...

Expanding Logo on Mobile with Javascript

I'm encountering some difficulties with the site. When viewing it on a mobile device or resizing the browser to phone size, if you scroll down and then back up, the logo appears oversized. I want it to remain small like it was at the beginning (refres ...

What is the best way to loop through an array of documents returned by Mongoose using Mongoose?

Within my server built on node.js (express based), there is a function that retrieves all users. Here is the function: export async function findAllUser() { let users = await User.find({}).exec() return users } In my node.js application, I have two m ...

Activate div2 visibility upon hovering over div1 using jQuery

I have a shopping basket on my website, and I want to display a list of products when a user hovers over the basket icon. However, I am facing an issue where the list disappears as soon as the mouse leaves the basket logo. Is there a way to keep the list ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...

PrimeFaces Issue with Redirection

Hello everyone, I am currently dealing with a redirection issue. Basically, I have an API that gets triggered when a user clicks on an image. This API captures the user's contact number and initiates a call through the software. Everything is functi ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

Please ensure that only one instance of a character, such as 'a', is entered into an ASP.NET textbox

I am working on a textbox that triggers the checkPostalCode function with the onkeypress event. <asp:TextBox ID="txtPostalCode" runat="server" CssClass="textbox-width form-control" onkeypress="return checkPostalCode(event,this)" TabIndex="14" MaxLength ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...

Issue with flexslider 2's continuous looping feature in one direction

I am attempting to create a continuous loop in Flexslider that moves in one direction only. When it reaches the last image, I want it to start over from the first image. I'm experiencing two issues with the example I've set up on jsfiddle: Firs ...

Is there a way to ensure that my JavaScript code remains permanent?

Is there a way to have the website remember the user's theme preference between visits? For example, if they choose the dark theme, can it automatically be loaded the next time they access the site? This is my current javascript code for handling the ...

Error: The provided content type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported in this context

I am currently attempting to create a post using JavaScript with AJAX to communicate with a Spring controller $("#crear").click(function () { var user = document.getElementById("user").value; var client = document.g ...

Effective Binding of Ember.js Controllers and Views (Doing it the Ember.js Style!)

Please forgive the length of this question, as I struggled to condense it. My current challenge lies in understanding the interplay between a controller and its view within Ember.js. Specifically, I am grappling with the concept of controller property and ...

Displaying data in a dashboard using Node.js arrays

I am currently working on the backend of my app using Node.js. My goal is to create a dashboard similar to those seen on platforms like Facebook and Instagram. Specifically, I want to display the users that a particular user follows. Once I have this lis ...

The ng-class dynamic remains static even upon resizing the window

The ng-class directive with a ternary statement works perfectly when the page initially loads. I am using the widthWindow.xs variable as my reference, which is set to "true" when the window size indicates mobile and changes to "false" on resize. However, e ...

AngularJS event that is triggered once all scopes have been applied

In my AngularJS application, I am retrieving data from a REST service. Occasionally, the brackets {{}} used to access values from scope are initially rendered and then replaced by the actual values later on. My goal is to add an ng-switch to the main DIV o ...