Troubleshooting the canLoad problem caused by returning an observable with a 404 error

I have implemented a check to call an API in the canLoad event for a module in my Angular application.

However, even if the API returns a 404 error in the network, my page continues to load. I want to change this behavior so that if a 404 error is encountered, the page should redirect to an error page.

canLoad(route: Route, segments: UrlSegment[]) 
{
       return this.http.get('testapi/getacces').pipe(map((response: boolean) => {
           if (response) {
               return true;
           } else {
               this.router.navigate(['/error']);
               return false;
           }
       }));
   }

While the code works as expected when the API is available, it does not handle the situation where a 404 error occurs. I am looking for a solution to properly handle the exception and route to an error page in case of a 404 error.

Answer №1

Utilize the catchError() operator to effectively manage error scenarios rather than successful responses.

Here's an example:

  canLoad(route: Route, segments: UrlSegment[]) {
    return this.http.get('testapi/getacces').pipe(
      map((response: boolean) => {
        if (response) {
          return true;
        } else {
          this.router.navigate(['/error']);
          return false;
        }
      }),
      catchError((error) =>
        of(error).pipe(
          map(() => {
            this.router.navigate(['/error']);
            return false;
          }),
        ),
      ),
    );
  }

This approach is helpful because a 404 Error response will not be caught by map, but it will trigger catchError, allowing you to handle Error responses accordingly.

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

Try utilizing MutationObserver to monitor changes in various nodes

I am faced with a situation where I have elements in my HTML that are dynamically populated with text from an API. My goal is to check if all these elements have a value and then trigger a function accordingly. The current code I have only allows me to obs ...

Ways to secure and conceal JavaScript functions or files from being accessed by users

Is there a way to protect my JavaScript methods from being easily copied by users? I am looking for a solution to hide my methods in firebug as well. Any suggestions on how to achieve this? Note: I am looking for methods to hide my code from users without ...

Exploring the Use of data- Attributes in SVG Circle Elements

Looking for a way to dynamically update the color of a Circle element in your SVG when it is clicked? You can achieve this by using jQuery's .css() method in conjunction with the data-* attribute. CHECK OUT AN EXAMPLE: STYLING IN CSS svg { height ...

What are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...

Guide on transferring input element to h3 tag without using the URL

Is there a way to update the h3 tag every time a user clicks without updating the tab URL? I only want to update the h3 tag. I have attached all files and a screenshot of the URL. <!DOCTYPE html> <html> <head> </head> ...

Is it possible to utilize router.push within Redux thunk? Is this considered a beneficial approach?

I have this anchor element: <a className="btn btn-sm btn-circle" href={`https://www.facebook.com/sharer/sharer.php?u=${ process.env.NEXT_PUBLIC_ENVIRONMENT == "prod" ? "https://tikex.com" : "https:/ ...

The scripts are mistakenly interpreted as stylesheets, but are actually being transferred with the MIME type text/html

Encountering two console warnings while using Chrome: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". domain/:11 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". ...

Crafting a variety of elements using Power BI's custom visual feature

I'm struggling with creating multiple objects based on input data. I've tried using an array, but it requires knowing the number of objects in advance. Does anyone have a solution for this? Here is my code snippet - module powerbi.extensibilit ...

What is the best way to store settings values permanently during the installation process in a react-native application?

I am looking for a way to save the settings of my app only during installation, rather than every time the app is opened, in order to prevent the options from resetting. I have tried searching on YouTube but most tutorials cover only user login persistence ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Is there a way I can conduct a search that includes both uppercase and lowercase characters simultaneously?

My current task is to create a search function that can search for elements in both lower and upper case, regardless of the case typed in by the user. I have attempted to implement a search feature that covers both upper and lower case scenarios, but it s ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

Learn how to retrieve data using the $.ajax() function in jQuery and effectively showcase it on your HTML page

Can someone assist me with extracting data from https://jsonplaceholder.typicode.com/? Below is the AJAX call I'm using: $.ajax({ url: root + '/posts/', data: { userId: 1 }, type: "GET", dataType: "json", success: function(data) { ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

The continuous declaration of scopes in AngularJS

Creating a website that features a variety of card games, each with its own controller. However, there are certain functions that are repeated across all the games. Is it feasible to consolidate this code into a single game? The inheritance process in Ja ...

Extracting the name of the file from the image's web address

I have created a simple Chrome extension for personal use and sharing with friends. I am dealing with URLs that have various formats, such as: i.imgur.com/abcd123.png or imgur.com/a2b3c78 or even i.imgur.com/herp321.png?1 All I need from these URLs are t ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

Looking to extract data from an HTML form?

In my HTML form, I am dynamically creating elements and setting their name and value attributes. When I try to access the value using document.formname.nameoftheelement.value, I receive an error stating that the value is undefined. I then attempted to us ...

software tool for managing state transitions

Can anyone recommend a superior javascript library for workflows? Right now, I'm utilizing Joint JS, but I require something with a more visually appealing interface (users tend to prefer that). ...