The page fails to redirect to the intended page when provided with an incorrect URL

I am currently working with an Angular function that I have provided below.

Function :

404.html file located in the root folder.

The issue I am encountering is that despite no errors appearing in the console, the URL in the address bar always reflects the last valid page clicked.

Could someone please point out where I might be going wrong and confirm if this approach for dynamic routing is correct?

Answer №1

The otherwise() part handles paths that do not match any specified routes.
In this scenario, the route matches but the template is not available at the given URL.
$routeProvider is unaware of this situation and can't take significant action.

To address this issue, you can somehow (details below) check if the template exists, and if it doesn't, use $location to redirect to an appropriate path (e.g. /error/404).

One method to determine page validity (i.e., template availability) is to try accessing the template (using $http) and handle any errors indicating template absence. However, relying solely on template existence for assessing a page's validity may result in misleading error messages during network or server issues, among other drawbacks.

A preferable approach could involve maintaining a list of "valid" pages and cross-referencing against it. If the current page should exist, proceed with fetching the template as usual. Otherwise, direct to an error page.

This logic can be implemented within the $routeProvider's resolve property to execute before controller instantiation and view loading.

For example:

var app = angular.module(...);

// Make this a constant so it can be injected into configuration blocks
app.constant('EXISTING_PAGES', [
  'page1',
  'page2',
  ...
]);

app.config(function configRouteProvider($routeProvider, EXISTING_PAGES) {    
  $routeProvider.
    when('/', {
      templateUrl: 'views/dashboard.html'
    }).
    when('/:page', {
      templateUrl: function getPageTemplateUrl(routeParams) {
        return 'views/' + routeParams.page + '.html';
      },
      resolve: {
        exists: function resolveExists($location, $route) {
          // Access parameters via `$route.current.params` since this runs before controller instantiation
          if (EXISTING_PAGES.indexOf($route.current.params.page) === -1) {
            // Redirect to suitable error page if the page is invalid/non-existent
            $location.replace();   
            $location.path('/error/404');
          }
          return true;
        }
      }
    }).
    // Define a separate route to redirect to
    when('/error/404', {
      templateUrl: '404.html'
    }).
    otherwise({
      redirectTo: '/error/404'
    });
});

Check out this brief demo as well.

Answer №2

If no other definition matches, the otherwise function is triggered. However, because your /:pages definition always matches, the otherwise function is not called. This means that the otherwise definition does not respond to a 404 error from the server when attempting to load the template.

To solve this issue, consider creating individual route definitions for each of your pages instead of using a generic one. For example: .when('/page1', ...) .when('/page2', ...) and so forth

Answer №3

When using redirectTo, it updates the $location which means you don't need to specify a .html file, just the routeParameter.

A better way to handle this is:

[...]
.when('/error', { templateUrl: '404.html' })
.otherwise({redirectTo: '/error'});

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

TypeScript - patiently anticipating the completion of nested for loops

Currently, I am working on a task that involves implementing two nested for loops in my code. The primary objective of the first loop is to make an API call, which is dependent on the IDs selected by the user. Unfortunately, the limitation of passing only ...

Discover the quick method of retrieving the checkbox value instantly

Looking for a way to track when a checkbox is checked using Angular This is the current setup: <div class="checkbox" ng-repeat="item in items"> <input type="checkbox" ng-model="test[item.id]" ng-click="getID()" ng-checked="checkAll"/> {{ ...

Is there a way to simultaneously redirect to a new page and trigger an event on that page?

As a programming novice and a newcomer to this community, I am seeking assistance with my query. I am interested in learning how to redirect from page 1 to page 2 and then immediately trigger an event on page 2. Below is the code snippet from page 1: & ...

How can we utilize node/express/jade to serve a specific Javascript file, depending on the availability of another file?

I've recently started developing web apps and I am facing a challenge. I have configured grunt to minify/uglify JavaScript, which works fine. However, I would like the server to check if the minified JavaScript file exists, and if it does, serve it. I ...

Using Masonry with AngularJS templates: A step-by-step guide

Hey there! I'm trying to incorporate masonry into my AngularJS project. I'd like the divs to flow from left to right within their container. The documentation suggests using the following code: <div class="js-masonry" data-masonry-options=&ap ...

Regular expression that detects a phone number which does not consist of a repetition of the same digit throughout

Looking for a regex pattern to match phone numbers that do not consist of the same number repeated throughout every part. Specifically, I need it to target 10-digit phone numbers in the format (123)123-1234. I have tried using this pattern, but it's ...

Enhance jQuery dataTable with live updates from Firestore querySnapshot

Currently, I have implemented jQuery dataTable in my project to display data from Firestore. While everything seems to be working fine, an alert keeps popping up in the browser whenever there is an update in the Firestore data: DataTables warning: table i ...

Is there a way to properly structure a JSON file for easy reading on localhost

I am having trouble with the formatting of my .json file while using backbone.js. I can't seem to pass in the url correctly. PlayersCollection = Backbone.Collection.extend({ model: Player, url: 'http://localhost/STEPS/data/players.js ...

Using Ajax to insert information into a row of a table

I am looking to update a table with data from a JavaScript function. The table is located in the same .jsp file but not inside the script. Using AJAX <script type="text/javascript"> function searchDetails() { $.ajax({ ...

Determining the current directory and file name in React and Webpack

Currently, I am working on a react js project and utilizing webpack and redux. Below is the organization of folders in my project: -assets -src -component -index.jsx -container -index.jsx My goal is to assign dynamic className to the inde ...

Implementing Winston logging into a React JS project

I am looking to integrate Winston logging into my React application that was created using create-react-app. First, I installed Winston by running the following command: npm install winston Next, I imported Winston into my app.js file like so: import win ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

What is the best way to remove a CSS style using JavaScript?

For my website automation using Selenium, I encountered a challenging dropdown that was not the standard native one but a custom-designed version. To tackle this issue, I needed to set its CSS class to hidden in order to access the native functionality smo ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

What is the reason behind combining all states into a single location in Redux, even if they are not globally accessible?

As a newcomer to React and Redux, I have found them to be quite enjoyable when used together in a small sandbox application. However, as I consider larger applications, I can't help but question why Redux stores the entire application state in a singl ...

Include additional select fields created through PHP

I have a dropdown menu on my HTML page that is populated by PHP from a MySQL database. echo "<select name='author_id[]' size='1'>"; foreach ($authors as $author) { echo "<option value=$author[id]>$author[ ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. https://i.sstatic.net/vJKM1.jpg The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, at ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

A step-by-step guide on including an object within an object array with Javascript

In the code snippet below, I have a JavaScript object that I'm trying to add a similar object to using request.rules[0]. request : [ rules: [ { pageFilters: [ { matchType: 'contains', type ...