Unusual navigation patterns in Angular

https://i.sstatic.net/kdh4A.png

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:

https://i.sstatic.net/7G09C.png

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

Dynamic content display using AJAX

Having already tried to find a solution through Google with no success, I am at a loss. I have articles where a paragraph is initially displayed, followed by a "read more" link which reveals more content using JavaScript. However, this approach may slow do ...

When the Next.js app is built, the API route provides the initial data, which typically occurs during development

I am encountering an issue with my Next.js page using App Router. The page retrieves data from its route API, which is obtained from MQTT. During development (running dev), when we send a request to api/getLocation, it returns updated data from MQTT. Howev ...

The login form is experiencing issues with submission when utilizing the submitFormHandler in ReactJS

In my single-page application, I'm working on creating a separate login page that will redirect the authenticated user to the main application. However, I'm encountering an issue where my submitFormHandler is not being invoked. The purpose of aut ...

Can the text color be customized to match the brightness level of the background area being covered?

Does anyone know of a plugin or method that can automatically change the color of text or swap predefined images/icons based on the average brightness of its parent element's background? If the background is dark, it should make the text white or swit ...

Issue with Bootstrap Toast failing to display after Bootstrap Modal closure

I am currently working on an app for a company directory that will help the company manage its employees, departments, and locations. This app is designed to allow users to make changes to the database only after confirming their actions. The app successfu ...

Retrieve the country code of an IP address using getJSON

I am currently facing an unusual issue. My goal is to extract the country code (like US for United States) from an IP address using free APIs. After some research, I came across ipify for retrieving the IP address (which works fine), and then attempted to ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

Guide on how to verify if a component with a specific name is registered within the Composition API of Vue 3

My current situation involves a template that loads dynamic components based on their names: <template> <div> <div> <div> <component :is="getFormRenderer" &g ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Internet Explorer 8 halts the progress of the loading animated GIF

When I call an animated loading gif image on an <asp:Button> click event in the client side code, the animation stops in IE8 while the server-side code is executing. This issue does not occur in Mozilla or other browsers. The animation works fine wh ...

The latest version of Next.js, Version 12, encounters an issue with theme-ui that results in the error message "code: 'ERR_REQUIRE_ESM'"

Encountering an error while working with Next.js 12 after creating a theme using theme-ui. https://i.stack.imgur.com/BtH7W.png Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\ind ...

Set up a Bootstrap date picker to populate two input boxes with a start and end date. Additionally, disable the ability for the date value to change

In my project, I have implemented Bootstrap Datepicker to set two input boxes for selecting start and end dates. The rule is that the start date must be after today and the end date must be after the selected start date. To disable specific dates in the da ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

Is there any benefit to fetching data in `{#await}` or `onMount` instead of `load` in SvelteKit, especially considering the impact on `+server`?

keyword: displaying loading spinner Imagine accessing a route like /dashboard, where most of the page content remains constant but certain sub-components require real-time data. If I retrieve this data within a load function, the entire route will remain ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Using jQuery to bind the "CTRL+A" key combination to exclusively selecting a specific region

My goal is to modify the CTRL+A shortcut so that instead of selecting all text, it will only select specific content within containers with a class of xyz. Unfortunately, I have not been successful in getting this functionality to work. Even attempting to ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

The issue arises when trying to use qtip2 in JavaScript upon page initialization

I successfully created a heatmap using JavaScript, utilizing a table with varying colors based on the displayed values' thresholds. To enhance user experience, I wanted to implement a popup window that shows additional information when hovering over a ...

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...