The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration:

$routeProvider
.when('/person/:person_id', {
  controller: 'person',
  templateUrl: 'partials/person.html',
  resolve: {
      data: ['api', '$route',
          function(api, $route) {
              return api('api/person/page/' + $route.current.params.person_id);
          }
      ]
  }
})
.otherwise({
  controller: 'error',
  templateUrl: 'partials/404.html',
});

In addition, we are confident that all controllers, views and API endpoints are in place.

Now, if we venture to a non-existing route like: blahblah/foobar, the router functions as expected by executing the 'error' controller and displaying the 404.html content.

Yet, when the resolution for /person/:person_id fails due to a 404 response from the API endpoint (indicating the person does not exist), Angular displays slightly unpredictable behavior - it skips running both the 'person' controller and the 'error' controller but still shows the 404 content correctly.

I am seeking a solution on how to make Angular trigger the 'error' controller upon resolution failure, similar to what happens with non-existing paths.

-EDIT-

Please note that, based on application constraints, using redirection is not an option.

The router must remain on the incorrect URL rather than redirecting to a specific 404 route.

Answer №1

According to the documentation regarding $routeProvider, if a resolve block fails, an event called $routeChangeError will be triggered. To handle this scenario, you can set up a listener for that event and then manually redirect to an error page by specifying a URL for it.

.otherwise ({
    url: '/ohmy',
    controller: 'error',
    templateUrl: 'partials/404.html',
});

You can include this logic in a module.run function like so:

angular.module('myModule').run(['$rootScope', '$location', 
    function($rootScope, $location) {
        $rootScope.$on('$routeChangeError', function() {
            $location.path('/ohmy');
        });
}]);

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

Is there a method to extract the y value for a specific x value that is not part of the current data set in a Chart.js graph

I have a set of data points like { x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }. With Chart.js, I can easily create a chart based on these points. Is there a method to retrieve the y value for a specific x value, such as 13, from the rendered chart? ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

Can the repeated use of AJAX function calls at regular intervals adversely affect the speed of the application?

On a specific page of my application, I have been using an AJAX function continuously as shown below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { $.ajax({ ...

React Redux fails to dispatch an action

Recently, I attempted to integrate Redux into my React application. I created a container called SignIn that instantiates a mapDispatchToProps and connects it to the component. The SignIn component renders a sub-component called SignInForm (code provided ...

How can data be displayed in AngularJS/Json without using ng-repeat?

It seems like I am required to use ng-repeat in order to display the data, but I would prefer to avoid using it. angular: App.controller('aboutLongCtrl', function ($scope, $http) { $http.get('test_data/ar_org.json') .then(func ...

The visualization rendered by ChartJS is not displaying correctly when data is fetched using an AJAX call

When it comes to creating visualizations from static datasets using ChartJS, I have no problems. However, the issue arises when I try to use data fetched via an AJAX call - the visualization does not render properly. Surprisingly, no errors are thrown even ...

Is there an Angular ui-router alternative to refresh $route?

I am in the process of switching from NgRoute to ui-router with angular 1.0.8. When dealing with nested views, I had to reload the routes which was straightforward with ngRoute. However, I am facing a similar issue with ui-router. Is there a comparable met ...

Is it advisable to subscribe to the entire database upon startup in Meteor?

Creating a Meteor app for the internal use of a company, I have designed it to track people and enable managers to assign tasks to various employees. Given the small size of the data being utilized, I anticipate that the database will not grow significantl ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

Tips on how to use console.log in react-simple-chatbot

I am currently working on a chatbot project and would like to add some features such as sending emails and popups. However, I am facing an issue with console logging elements in my code. Here is the snippet of my code: import React from "react"; ...

Is it possible to conceal and completely empty the TextBox once the checkbox is deselected?

When the checkbox is checked, the textbox is displayed; otherwise, it remains hidden. However, the value is not being cleared. Can someone please help me with this issue? Thank you in advance. HTML <div class="munna"> <in ...

Tips on how to modify database records rather than generating new ones

Currently, my team is developing a web application that utilizes wearables to monitor vital parameters. As part of our integration testing, we are using a Fitbit device. The app itself is built with Angular and JavaScript, while the database is hosted on C ...

Vue - Continue to fetch all items asynchronously within a for loop

I am facing a challenge where I have an array of data that needs to be fetched using a for loop. However, I want to fetch this data asynchronously to make multiple calls at the same time. Additionally, once all the data has been fetched, I need to perform ...

Step by step guide on using PHP Curl to easily register a new user on an AngularJS website

Looking for assistance from someone knowledgeable in PHP and AngularJS to assist with parsing a registration page in order to create a Curl Function. I am currently working on establishing a Single Sign On feature with a partner website. Once users regist ...

Tips on elevating a dragged div above all other elements when utilizing two scrollbars

Currently, I have two horizontal scrollers where I need to drag a div from the upper scroller to the lower scroller. While this functionality is working properly, there is an issue with the dragged div getting lost under the borders of the scroller during ...

Guide on creating a sitemap using Express.js

I've been working with the sitemap.js package from https://www.npmjs.org/package/sitemap While I can add URLs to the sitemap manually, my challenge lies in adding URLs based on data retrieved from MongoDB. Since fetching data from MongoDB is asynchro ...

What is the process for selecting the Node version when installing with .nvm?

I am having an issue with nvm in the terminal. When I try to run npm install <something>, it always installs the package in node version 9.4.0, regardless of the version set using nvm. Even after switching to node version 10.15.3 using nvm use v10.1 ...

Issue with React sending a Get request to a Node server using Express

Here is a snippet of code from my React app where I am trying to retrieve data from my database based on a value that is passed. Let's start by examining the section of code that may be causing an issue: Within one of my forms, there is a function th ...

Locate the word or phrase without a comma

I am currently working on a code that involves finding keys with string values separated by commas. var db = { "name": "Nkosana", "middle": "Baryy", "surname": "walked", "batch_number": "test,b", "temp": ",,67,6,87,86,5,67865,876,67" ...