Observing the route parameters in an Observable stops once a 404 error is triggered from another Observable within a switchMap

In my current scenario, I am monitoring the parameters of the active route in order to update the content being displayed.

Within my component's ngOnInit() function, I have implemented the following logic:

this.activeRoute.paramMap
      .pipe(
        switchMap((params) => {
          this.fileName = String(params.get('filePath'));
          return this.fileService.checkIfFileExists(this.fileName);
        }),
        tap((result) => {
          if (!result) {
            this.router.navigate(['/']);
          }
        }),
        filter((result) => result),
        switchMap(() =>
          this.modificationService.getFileModifications(this.fileName)
        ),
        tap((result) => {
          if (result.allModifications) {
            this.modificationList = result.allModifications;
            this.noModification = false;
          }
        })
      )
      .subscribe();

Providing more context:

  • If the file does not exist: the router redirects the user to /
  • If the file exists, there are two scenarios:
    • Modifications are found: they are displayed
    • No modifications are found, a 404 error is triggered, which should display "no modifications found" on the website

The current behavior is as follows:

  • If I navigate to a page for a file with modifications, they are displayed correctly
  • Upon switching to another file that also has modifications, the display updates accordingly
  • However, when switching to a file with no modifications and receiving a 404 error, the observable ceases to function. The content remains stuck on the last file with modifications displayed, even though the URL (and filePath parameter) changes

I navigate between files using a menu without refreshing the page. It works fine after a manual refresh.

Although I attempted to use catchError() from RxJS, it did not alter the behavior other than suppressing the error message in the console.

Previously, I had only implemented:

this.router.routeReuseStrategy.shouldReuseRoute = () => false;

Instead of utilizing the deprecated code block this.activeRoute.paramMap..., which I prefer not to use. The paramMap Observer functions smoothly in my other components that do not deal with 404 errors.

Any assistance would be greatly appreciated :)

Answer №1

The 404 error response generated by the modificationService is triggering the completion of your stream. When the switchMap operator switches to the inner stream and encounters an error, it causes the outer stream to complete as well.

Once a stream has completed, it becomes static and no longer responds to any new emissions. To work around this issue, you need to handle the error and return a new stream to prevent the error from affecting the overall process.

this.activeRoute.paramMap
  .pipe(
    switchMap((params) => {
      this.fileName = String(params.get("filePath"));
      return this.fileService.checkIfFileExists(this.fileName);
    }),
    tap((result) => {
      if (!result) {
        this.router.navigate(["/"]);
      }
    }),
    filter((result) => result),
    switchMap(() =>
      this.modificationService
      .getFileModifications(this.fileName)
            .pipe(
              // handle error and return a new observable
              catchError((err) => {
                console.error(err);
                return of(null);
              })
            )
    ),
    tap((result) => {
      if (result.allModifications) {
        this.modificationList = result.allModifications;
        this.noModification = false;
      }
    })
  )
  .subscribe();

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

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

The Angular HttpClient Service will exclusively provide responses that have a status code of 200

I'm facing an issue with my login component where it calls an http client service to send a request to the server for logging in. Everything works smoothly when I enter valid credentials, but if I input wrong credentials, the service doesn't seem ...

Unable to find the <a> element with a numerical id attribute in Playwright. The selector '#56' is not recognized as valid

Seeking to identify and target the <a> element with an id attribute. Attributes that may be used: role href title id style onclick I am able to do so using role and name, but unsuccessful with id or onclick. The latter two would be beneficial for f ...

"I am looking to retrieve the properties of an object that belongs to the EChartsOption type in TypeScript when working with Angular and ECharts. How

Currently, I am exploring how to access a property of an EChartOptions object in Angular 16.0.2, which may be undefined as I am still new to TypeScript. List of npm packages: eapp/src$ npm list <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

What is the appropriate typescript type for an array payload when using the fetch API?

My current method involves using fetch to send URL encoded form data: private purchase = async () => { const { token } = await this.state.instance.requestPaymentMethod(); const formData = []; formData.push(`${encodeURIComponent("paymentTok ...

Invoking method in Angular component upon receiving a notification via ActionCable

Currently, I am practicing the utilization of ActionCable within Angular. To begin, I set up a rapid Rails application on Heroku, followed by creating an Angular application with the actioncable npm module integrated as a dependency. For experimentation p ...

TypeScript: Despite declaring specific types, generic functions still treat parameters as "any"

When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any when working with functions that involve generics. Here's a si ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

Decoding request header in Angular during app initialization

Currently, I have three domain names registered with Godaddy and they are all directing to the same server that is hosting my Angular 2 application. I am curious if there is a method to examine the request header in order to identify which of the three d ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Extract JSON values based on a given condition

I am working on a Typescript project that involves an array and a JSON object. I need to extract the value of a property from the object based on another property's value being in the array. Here is the array: let country: string[] = [ 'AR' ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

Inquiry into Angular: How to load Angular components dynamically and handle state management separately

Our Angular application is set up for business transactions with one NgModule and a custom state management system using Behavior Subject service to notify components of any state changes. We now need to allow users to add multiple transactions, requiring ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...

Can you use getters and setters in a TypeScript declaration file?

I am facing an issue with a declaration file for the openUi framework. The framework utilizes a get<propname>() and set<propname>(var) syntax for its properties. In traditional JavaScript, the setup would look like this: sap.ui.getCore().atta ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Why isn't Nodemon monitoring the directory in webpack-typescript-node.js?

Here are the contents of the package.json file for a TypeScript project using webpack and node.js: "scripts": { "build": "webpack", "dev:start": "nodemon --watch src --exec \"node -r dotenv/co ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...