Unusual navigation patterns in Angular

My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything' refresh properly. However, when I refresh the page in '/dashboard/anything' routes, the angular app fails to load and only the views' html remains. I have tried various solutions but can't seem to explain this strange behavior.

Here's what happens on refresh:

The routing in my app looks like this:-

angular.module('dashboard', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
    $routeProvider

    // route for the dashboard home page
        .when('/dashboard/login', {
            templateUrl: 'dashboard/login/index.html'
        })
        .when('/dashboard', {
            templateUrl: 'dashboard/home/index.html'
        })
        ...
})

And the routing in node is as follows:-

router.get('/dashboard', function(req, res) {
  res.sendFile('/dashboard/index.html',{ root: path.join(__dirname,  '../public') });
});

router.get('/dashboard/*',function(req, res) {
  console.log("Here");
  res.sendFile('/dashboard/index.html',{ root: path.join(__dirname, '../public') });
});

Update:- More code snippets. Two angular apps are set up at two different routes. The app at the root level works perfectly, but the one at the /dashboard level has issues.

...

Answer №1

Be cautious when mixing actual file URLs (such as templates) and pseudo routes for Angular. If you are doing this, there might be a conflict where Angular tries to load a template file like dashboard/users/reports.html, but the wildcard route in Express /dashboard/* ends up returning the /dashboard/index.html file instead. It's advisable to keep them separate to avoid such issues:

In Node.js:

router.use('/templates', express.static(path.join(__dirname, 'path/to/templates')));

router.get('/dashboard', function(req, res) {
  res.sendFile('/dashboard/index.html',{ root: path.join(__dirname, '../public') });
});

router.get('/dashboard/*',function(req, res) {
  console.log("Here");
  res.sendFile('/dashboard/index.html',{ root: path.join(__dirname, '../public') });
});

In Angular:

.when('/dashboard/images', {
    templateUrl: '/templates/dashboard/media/index.html'
})

Answer №2

Below is the code snippet from my app.js file:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var viewRoute = require('./routes/view'), //defining routes
    apiRoute = require('./routes/api'),

app.set('views', path.join(__dirname, 'views'));  //setting to HTML engine instead of EJS | JADE 
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', viewRoute);   //using middleware for routing
app.use('/api', apiRoute);

I have defined two main things :

  1. View -- Rendering for HTML files
  2. Api -- Code for handling get / post request from views (HTML files)

Let's take a look at the view.js file

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

router.get('/home', function(req, res, next) {
  res.render('pages/home');
});

router.get('/login', function(req, res, next) {
  res.render('pages/login');
});


router.get('/about', function(req, res, next) {
  res.render('pages/about');
});

module.exports = router;

Now let's explore the api.js file :

var express = require('express');

module.exports = (function() {

    'use strict';

    var api = express.Router();

    api.get('/home', function(req, res, next) {
      console.log("A GET Request for Home Page\n");
    });


    api.get('/dashboard', function(req, res, next) {
      console.log("A GET Request for About Page\n");
    });

    api.get('/about', function(req, res, next) {
      console.log("A GET Request for About Page\n");
    });

return api;

})();

Next, let's check out my AngularJs Controller File for routing :

$routeProvider
        .when('/home', {
            templateUrl: '/home',
            controller: 'homeCtrl'
        })
        .when('/login', {
            resolve : {
                'check' : function ($location, $cookies){
                    if ($cookies.get('isAuthenticated') && $cookies.get('current_user')) {
                        $location.path('/dashboard');
                    }
                }
            },
            templateUrl: '/login',
            controller: 'loginCtrl'
        })
        .when('/dashboard', {
            resolve : {
                'check' : function ($location, $cookies){
                    if (!$cookies.get('isAuthenticated') || !$cookies.get('current_user')) {
                        $location.path('/login');
                    }
                }
            },
            templateUrl: '/dashboard',
            controller: 'dashboardCtrl'
        })
        .otherwise('/home');

Lastly, in my controller files I handle user navigation after login and set permissions:

myApp.controller('homeCtrl', function ($interval, $rootScope, $scope) {
    //Displaying HOME page
});

myApp.controller('loginCtrl', function ($scope) {
    //DISPLAYING LOGIN PAGE FOR LOGIN
    //YOUR LOGIN CODE GOES HERE AND AFTER THAT DO:
     $location.path('/dashboard/*'); //depending on you
});

smpApp.controller('aboutCtrl', function ($interval, $rootScope, $scope) {
    //DISPLAYING YOUR ABOUT US PAGE
});

Key points to note:

  1. Routes are authenticated every time.
  2. Separate files for viewing HTML and handling requests.
  3. Distinct controllers for each functionality.
  4. Usage of $location.path for user redirection to dashboard.

Thank you & Cheers!

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

Resolving the CORS predicament caused by the ionic/angular's HTTP interceptor

I am currently using Ionic for both web and mobile development. However, I have encountered a CORS issue when integrating it with an HTTPS URL. Interestingly, the issue seems to be resolved after removing the HTTP interceptor. Nevertheless, I am seeking a ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...

Ways to enhance filtering capabilities in AngularJS?

Currently, I am using the following ng-model: <input ng-model="query" type="text" iplaceholder="Add New Filter"></input> This is how I am presenting my data: <ul> <li role="menuitem" ng-repeat="item in availableFilters | filter:qu ...

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

You can activate the ability to click on the main tag by setting routerlink as the child component in Vue

Within my HTML code, I have utilized a RouterLink within an li tag to create a basic dropdown menu. Currently, when options are displayed in the dropdown menu, I am only able to click on the text itself to navigate to the next page. However, I would like t ...

What is the best way to retrieve the parent div's ID with JavaScript and Selenium?

My current project involves utilizing webdriverjs, and I am faced with the challenge of retrieving the parent id of a specific webelement among multiple elements with similar classes. Each element has a different id that gets dynamically generated when a m ...

Troubleshooting a problem with Angular routing when trying to access a specific URL using

My main objective is to enable users to view products by clicking on the item itself. For each product item displayed in main.html, the URL format is like this... <a href="/products/{{ product.id }}">{{ product.title }}</a> For instance, when ...

I'm trying to wrap my head around Ruby's "super" keyword in the scenario of super(options.merge(include: :comments)). Can you help explain

When combining AngularJS with RoR, I have come across examples of using code similar to the following in model files: def as_json(options = {}) super(options.merge(include: :comments)) end My understanding is that this code allows the JSON object ...

Error: The function expressValidator is not recognized in the current environment. This issue is occurring in a project utilizing

I am currently working on building a validation form with Express and node. As a beginner in this field, I encountered an error in my console that says: ReferenceError: expressValidator is not defined index.js code var express = require('express& ...

What is the process for updating the h1 header with text entered into an input field?

I'm working on an assignment that requires me to change the h1 heading to reflect whatever is entered into the input field. To accomplish this, I need to create a function using getElementByID. Here's what I've done so far: <!DOCTYPE htm ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Begin the jQuery ResponsiveSlides Slider with the final image in the <ul> list

Currently utilizing the responsiveSlides image slider from responsiveSlides on our website. This jQuery slider uses an HTML unordered list of images to slide through automatically. The issue I'm facing is that before the slider actually starts (meani ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

bitcoinjs-lib for generating raw transactions in Node.js

var bitcoin = require('bitcoinjs-lib'); var rp = require('request-promise'); var data = Buffer.from('Hello World', 'utf8'); var testnet = bitcoin.networks.testnet; var privateKey = 'p2pkh'; var SourceAddre ...

Enhance your ng-boilerplate by incorporating angular ui bootstrap 3

Recently, I integrated Bootstrap 3 into my AngularJS v1.2.0-rc.3 project that is based on ng-boilerplate. However, I encountered an issue where grunt fails during the karma tests execution. After some investigation, I discovered that the problem lies in ...

Unable to utilize library post npm import

Recently, I attempted to integrate the flexibility library into my Laravel project. Following the installation with npm i flexibility --save, I required it in my app.js file: require('flexibility/flexibility.js'); ... flexibility(document.docume ...