Navigating back in Angular5 without losing data

While working with Angular5, I have encountered an issue where I lose data when trying to go back in the browser. Essentially, I want the previous component to be loaded with its data intact.

For example:

Here is a snippet from my component:

import { Location } from '@angular/common';
@Component({
  selector: 'app-mant-cert-certificacion',
  templateUrl: './mant-cert-certificacion.component.html',
  styles: []
})

export class MantCertCertificacionComponent implements OnInit {

constructor(private location: Location) {
  }
goBack() {
    this.location.back();
    console.log( 'goBack()...' );
  }
}

And here's how it's implemented in the HTML file (mant-cert-certificacion.component.html):

<a href="javascript:void(0)" (click)="goBack()">
            <- Back
</a>

When this component is called from my router module, I want to make sure that clicking on the "go back" button loads the previous component along with its data.

This is how my router module looks like:

export const routes: Routes = [
  { path: 'xxxx', children: [
    { path: '', component: XComponent},
  ]},
  { path: 'yyyy', children: [
    { path: 'contractdetail/', component: MantCertCertificacionComponent}
  ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MantenedoresCertRoutingModule { }

Any suggestions on how to achieve this?

The previous component in question would be "XComponent". The specifics of the data don't matter, I simply need it to load properly. Thank you!

Appreciate any help provided.

Answer №1

If you're looking for a way to store data that persists during navigation, here are some options:

  1. LocalStorage
  2. sessionStorage
  3. Services

localStorage and sessionStorage essentially do the same thing and have similar APIs. However, with sessionStorage, the data is only saved until the window or tab is closed. On the other hand, with localStorage, the data remains persistent until the browser cache is manually cleared or your web application clears it.

I recommend using @ngx-pwa/local-storage, which provides asynchronous local storage for Angular.

For Angular 5:

npm install @ngx-pwa/local-storage@5

Add it to your RootModule

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

Inject and utilize it

import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

How to use it

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});

Services
Create a Service and Register it with an Angular module.

why? If you want an instance of a dependency to be shared globally and share state across the application you should configure it on the NgModule.

Sharing Data with BehaviorSubject

Answer №2

Angular keeps track of route information in its navigation history.

window.history.back();

Executing this should be successful.

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

Issues with Angular 5 application functionality on IOS8 using Browserstack

I encountered an issue while testing my Angular 5 app on an iPhone 6 with IOS8 (Safari) and in Browserstack. The app fails to run, only showing an empty page along with a Javascript error. Any advice or suggestions on how to resolve this? https://i.sstat ...

Tips for utilizing generated *.d.ts files

I have been utilizing a Visual Studio 2017 extension called TypeScript Definition Generator to automatically create TypeScript interfaces for my MVC-ViewModels. Despite trying various similar tools, they all seem to result in the same output (*.cs.d.ts-Fil ...

modify the inherent CSS property

I am working with a component that I have inherited, including its CSS style, and I need to modify one of its properties. Current CSS: .captcha-main-image { width: 100%; height: auto; } <img class ="captcha-main-image" id="captchaImage" src= ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

Encountered an issue resolving the dependency while executing npm i

I encountered an issue while trying to run the npm i command: npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a ...

From the service to the component, navigating the array in Angular

I'm encountering difficulties with Angular Services and I can't seem to pinpoint the issue. Currently, I am working on a book application that utilizes Promises. To enhance performance, I am restructuring my code by implementing service injectio ...

Understanding the expiration date of a product

I'm seeking assistance with identifying expiration dates from a list of data. For instance, if I have a list containing various dates and there is an expireDate: 2019/11/20, how can I highlight that date when it is 7 days away? Here's an example ...

Constructing a hierarchical tree structure using an array of objects that are initially flat

My goal is to create a hierarchical tree structure from a flat array: The original flat array looks like this: nodes = [ {id: 1, pid: 0, name: "kpittu"}, {id: 2, pid: 0, name: "news"}, {id: 3, pid: 0, name: "menu"}, {id: 4, pid: 3, name: ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Secure Your Angular Application on Heroku with Best Security Practices

I am encountering an issue with my Angular application routing: const routes: Routes = [ { path: '', component: HomePageComponent }, { path: 'rome-routing', component: SomeRoutingComponent}, { path: 'other-routing', comp ...

Identify the category of the component

Using a Link component from version 4.0.0-beta.2, I am exploring its capability to override the root element with a field called component. My goal is to wrap the Link component in a new component called MyLink and pass a custom component through props: ...

Error: Unable to access the 'push' property of null when handling multiple requests

I am in the process of creating an Angular Node application rating system. Within this system, I am attempting to iterate through an array of IDs that were sent to the server via a POST request and push those IDs using a for loop into the "users need to ra ...

Error Encountered When Searching for Modules in a Yeoman-Generated Express TypeScript Project

After generating an express typescript project using yeoman, I encountered some errors whenever I tried running the application. The errors stated that it could not find modules such as "morgan", "body-parser", and "cookie-parser". Even though these module ...

Error message "ERR_NO_ICU" appears when trying to run the command "ng serve

I am currently working on a website project using Spring Boot and Angular, but I am encountering some challenges when trying to start Angular's live development server. The error message I receive is the following: ubuntuserver]#> ng serve internal ...

What is the most effective way to add cookies to the response object in a NestJS GraphQL application?

How can I save cookies in the response object of a NestJS GraphQL application? Here is the relevant code snippet: app.module.ts: GraphQLModule.forRoot<ApolloDriverConfig>({ autoSchemaFile: true, driver: ApolloDriver, cors: { ...

Ways to resolve the error 'Node Sass unable to locate a binding in your current environment' while executing npm run build

When executing sudo npm run build, I encountered an error stating that it cannot find the binding for sass. My npm version is currently 11.13.0 and I have only one version installed. I have tried various solutions such as npm install node-sass, npm rebui ...

Utilizing properties in a fresh function with Angular 2

Having an issue with the beacon Minor propriety in a new function. The editor keeps saying that the name cannot be found, and I'm not sure how to resolve it. Function Example: listenToBeaconEvents() { this.events.subscribe('didRangeBeacons ...

In Angular 6, users need to click twice for anchor scrolling to function properly

I've set up a simple layout on a really long page: <a href="/technicalmanagerreport/4e8485d9-5751-4684-9d24-0af2934dd390#h2">test</a> <h2 id="h2">LOL</h2> The issue I'm facing is that the first time I click the link, it ...

Implementation of setProperties method on LineLayer in MapBox encounters resolution issues

I am currently utilizing the Android Mapbox SDK to integrate a VectorSource into a MapboxMap and then I am trying to incorporate a LineLayer onto the map as well. My version is 5.1.3 This code will be written in TypeScript due to its compatibility with t ...