"Enhance your Angular JS experience with dynamic URL parameters and personalized redirection for improved URL accessibility

I'm struggling to make this code function properly:

 .....
   .when('/channel/:id/:slug',{
            templateUrl:'views/channel/index.html',
            controller:'Channel',
            publicAccess:true,
            sessionAccess:true
          })
   .....
    app.controller('Channel', ['$scope','$routeParams', function ($scope,$routeParams) {

    }]);


    app.run(function($rootScope, $location, $route) {

      var routesOpenToSession = [];

      angular.forEach($route.routes, function(route, path) {
        console.log(path);
        console.log(route);
        route.sessionAccess && (routesOpenToSession.push(path));
      });

      $rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {

        var closedToSession = (-1 === routesOpenToSession.indexOf($location.path()));

        if(closedToSession && $rootScope.session.id_user) {
          $location.path('/');
        }
      });
    });

Can anyone explain why I am unable to access the page using site.com/channel/9/my-slug even when $rootScope.session.id_user exists and sessionAccess:true is set?

Whenever I try to access it, I get redirected to /, while other static URLs work fine with sessionAccess:true. For example channel/staticparam works, but dynamic parameters cause issues.

Here is the result from the console log:

Answer №1

Apologies for the confusion, here is the revised code:

/*Handling redirects for logged and not logged users*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location,$route) {

   var publicRoutes = [];
   var sessionRoutes = [];

    angular.forEach($route.routes, function (route, path) {
      if(route.publicAccess){ 
        publicRoutes.push(route.regexp);
      }
      if(route.sessionAccess){
        sessionRoutes.push(route.regexp);
      }
    });

    $rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {

     var nextRouteRegexp = nextLoc.$$route.regexp;
     
     //redirect for not logged in users
     if(publicRoutes.indexOf(nextRouteRegexp) < 0){
      $location.path('/auth/login');
     }

     //redirect for unauthorized session users
     if(sessionRoutes.indexOf(nextRouteRegexp) < 0 && $rootScope.session && $rootScope.session.id_user ){
      $location.path('/');
     }

    });
}]);

I realized that it was essential to check the route regexp instead of the static URL path.

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

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...

Connecting with a php anchor and hash symbol in a website URL

Looking to include a PHP anchor along with a hash anchor in an HTML link. <?php echo '<a href="test.php?page='.$i.'#hash">'.$i.'</a>'; ?> The PHP code successfully echoes the link, but upon clicking it, th ...

Leveraging AJAX within a RESTful API in a Node.js environment to retrieve a JSON file and dynamically parse its contents according to the specific button selected on the front-end interface

Can anyone help me with understanding the communication process between server.js (Node.js) and the front-end JavaScript file? I am trying to implement AJAX as a RESTful API in the server to retrieve a JSON file, parse it based on specific button clicks in ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...

Different ways to showcase the date in various styles using ng-repeat in AngularJS

I have a date stored as "2017-04-03 05:00:07". I want to determine if this date falls on today's date. If it does, I want to display it as "today" followed by the exact time. If the date is from yesterday, I would like it to be displayed as "yesterda ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

Certain javascript files have had illegal characters mistakenly added to them

There seems to be an issue with the js files or server on certain pages, as they are not loading in Firefox: with firefox: SyntaxError: illegal character 癡爠浥湵楤猠㵛≶敲瑩捡汭敮產崻 ⽅湴敲⁩搨猩映啌敮畳Ⱐ獥灡牡瑥 ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

Share user group Node Express with relevant data

I am looking for a way to create and send a customized navigation object to be rendered in an Express application based on user groups. My current approach involves adding middleware to each route: var navMiddleware = function() { return function(req, ...

Switch the design and save it in the browser's cache

Exploring the possibility of having two themes, "dark" and "light," that toggle when a checkbox is clicked. To implement the theme change, I used the following JavaScript code: document.documentElement.setAttribute('data-theme', 'dark&apos ...

Guide to setting up and launching a JavaScript/Vue GitHub repository on your local machine

I have a cloned app located here: cvss-v4-calculator that I want to run locally for debugging with VS Code or a similar tool. However, I'm encountering difficulties in setting it up. I've been attempting to run this as a web page using node.js, b ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Using PHP and XML with Ajax can run into problems with the getElementsByTagName function in Internet

Encountering a problem with getElementsByTagName specifically in IE versions 7 and 8. An address lookup generates suggested addresses as XML strings stored in a PHP session variable. These are then accessed using an AJAX function to retrieve the desired s ...

Failed to connect to Wordpress REST API when calling it from a NextJS server due to ECONNREFUSED error

I am currently working on a basic example that involves fetching a list of page slugs from the WordPress REST API, but I am encountering some unexpected behavior. My getPageList() function is an asynchronous function that makes a simple call to the WP API ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

What is the procedure for turning off hover color on an href element?

Working on a website that utilizes MUI components, I have incorporated href into the Tab elements within the navigation bar. <Tab label={element} id={index} sx={{display: {xs: 'none', md: 'inherit'}}} href={`#${navElements[element ...

What is the best method for utilizing a single L.Shapefile/zip file Object and modifying the onEachFeature function for each layer?

I am currently facing an issue where I have multiple tileLayers each containing a shape file. These tile layers represent different datasets based on variables and adjust colors accordingly. I have been able to achieve this by creating three separate Obje ...

Understanding the Event Context of Elements using Browser Development Tools

I'm currently investigating the functionality of the search feature on the React Documentation page: https://reactjs.org/ . It's known that they utilize DocSearch, but I'm interested in understanding the inner workings. At the moment, I&ap ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...