Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet:

navigateToDetail(entity: User) {

  const navigationExtras: NavigationExtras = {
    state: {
      entity,
      entityId: entity.id
    }
  };

  this.router.navigate([RouteNames.users, entity.id], navigationExtras);
}

On my detail-page-base, I retrieve the routing parameters as shown below:

constructor(protected route: ActivatedRoute, protected router: Router, protected baseProvider: ApiResourceBaseService<T>) {
  this.route.queryParams.subscribe(params => {
    if (this.router.getCurrentNavigation().extras.state) {
      this.entity = this.router.getCurrentNavigation().extras.state.entity;
    }
  });
}

While this setup works fine under normal circumstances, I encounter an issue where the parameters become empty when navigating back using the browser and then navigating forward again.

What would be the best approach to handle navigation in angular 7 in such scenarios?

Answer №1

To resolve the issue, I connected to the router events and reverted the data back to its original value.

this.router.events
        .pipe(filter((event: NavigationEvent) => (event instanceof NavigationStart)))
        .subscribe(( event: NavigationStart ) => {

          console.group( 'NavigationStart Event' );
          // Each navigation sequence is assigned a unique ID. Even "popstate"
          // navigations are essentially "roll forward" navigations with
          // a new, unique ID.
          console.log('navigation id:', event.id);
          console.log('route:', event.url);
          // The "navigationTrigger" can be one of:
          // --
          // - imperative (eg. user clicked a link).
          // - popstate (eg. browser controlled change like Back button).
          // - hashchange
          // --
          // NOTE: Uncertain about what triggers the "hashchange" type.
          console.log('trigger:', event.navigationTrigger);

          // When the navigation event is triggered by a "popstate" event (e.g., back / forward
          // buttons), the "restoredState" property is defined. It contains the ID of the earlier navigation event
          // that the browser is reverting to.
          // --
          // CAUTION: This ID may not be part of the current page rendering.
          // This value is retrieved from the browser and may persist across
          // page reloads.
          if ( event.restoredState ) {
            this.router.getCurrentNavigation().extras.state = event.restoredState;
            console.warn('restoring navigation id:', event.restoredState.navigationId);
          }
          console.groupEnd();
        });
}

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

Even after applying trim() function, PHP's return statement still adds spaces unnecessarily

My function is supposed to return a boolean, but for some reason, it is adding spaces at the beginning of the string. Even after using trim(), the spaces persist. What could be causing this unexpected behavior? PHP function checkFile($v){ $result = is_ ...

Errors occurred when trying to use Jquery to handle a JSON response

enter code here function customPaging(action, action1, page) { alert("in customPaging"); $.getJSON("./paging.do?action="+escape(action)+"&p="+escape(action1)+"&str="+escape(page), function(data){ alert("Length: "+data.length); var options = ...

A guide on utilizing ClassName to insert new items into a DIV

Original HTML code: <span class="specLink"> <specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty> </span> <br /> <span class="specLink"> <specialty2><a titl ...

What could be causing my Three.js code to fail during testing?

Recently, I decided to delve into the world of Three.js by following a thorough tutorial. While everything seemed perfectly fine in my code editor of choice (Visual Studio Code 2019), I encountered a frustrating issue when I attempted to run the code and n ...

How can I use JavaScript regex to extract the first term to the left of a specific symbol?

Having a string in this format str = "Is toffee=sweet?" I need to retrieve the first term on the left side of =, which in this case is toffee. To accomplish this, I use the following code snippet: str.split("=")[0].split(" ").splice(-1,1)[0] This retu ...

Manipulating State in React: How to add a property to an object within an array within a component's state

Currently, I am retrieving an array of objects stored in the state, and I am attempting to include a new property to each of these objects. However, I am encountering a problem where even though I can see the new property being added to each object, when ...

Issue encountered with ASP.Net Core on AWS Serverless: The middleware for the SPA default page was unable to locate and return the default page '/index.html'

Everything works flawlessly with my ASP.Net Core 6.0 application with Angular on Visual Studio, but once deployed to AWS Serverless and accessing '/', an error occurs. The default SPA page middleware cannot serve the default page '/index.h ...

What is the best way to transfer values from an AJAX script to the rest of the Javascript code?

Currently, I am diving into the world of a django 2.0 template along with a third-party jQuery script used for tagging photos and my own JavaScript code that acts as the "glue." Despite being new to JavaScript and JQuery, I managed to make a successful aja ...

Challenges of performance in EmberJS and Rails 4 API

My EmberJS application is connected to a Rails 4 REST API. While the application is generally working fine, it has started to slow down due to the nature of the queries being made. Currently, the API response looks like this: "projects": [{ "id": 1, ...

Leveraging the power of a JavaScript framework within the script tag

Hello there! I'm just starting out with vue.js and exploring different JavaScript frameworks. Recently, I came across an interesting example based on the documentation. import modal from 'vue-semantic-modal' export default { components ...

The progress bar in Java Script is static and cannot be customized to change colors

Trying to use HTML for image uploads and I've created Java code to monitor the progress of the upload. However, I'm facing an issue where I cannot change the color of the progress loading bar. Below is the code I am currently using for uploading ...

Is there a way for me to properly type the OAuthClient coming from googleapis?

Currently, I am developing a nodemailer app using Gmail OAuth2 in TypeScript. With the configuration options set to "noImplicitAny": true and "noImplicitReturns": true, I have to explicitly define return types. Here is a snippet of my code: import { goog ...

What is the correct approach to importing the Select class in JavaScript with WebDriver?

I'm having trouble using the Select function in my code to interact with a dropdown menu. I attempted to import Select from the "selenium-webdriver" package, but it doesn't seem to be working. All of the search results I've found on this top ...

Node.js server experiencing delays due to V8 processing constraints

REVISED I am currently running a nodeJS http server designed to handle uploads from multiple clients and process them separately. However, I have encountered an issue where the first request seems to block any subsequent requests until the first one is co ...

'ng build' operation halted - Angular

Having issues running ng build in order to generate my /dist folder for hosting on a remote server. While npm install went smoothly, the ng build command keeps aborting. Here is the error message: ng build[3725390]: ../src/node_worker.cc:525:static void ...

Invoke Selenium using JavaScript

Imagine I have this (fictional) JavaScript snippet: asynchronousOperation.addEventListener("completed", function (event) { if (event.property == "required value") tell Selenium we are good; else tell Selenium the test failed; }); ...

Using PHP to validate a read-only textbox

I am trying to implement validation on a Datepicker that is set to readonly, but I am facing issues with my current code. Can someone please assist me? Below is the JavaScript code used for error trapping: <script type="text/javascript"> $(func ...

Establish a connection between servers operating on two distinct ports

I'm completely new to JavaScript and developing web applications. I have set up two servers on my computer running on separate ports (5000 and 5001). The server on port 5000 needs to communicate with the one on port 5001, but I'm struggling to g ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...