3

I'm using Angular5 and i can't go back in the browser without losing data. I mean, that the previous component, could be loaded with their data again.

Example:

In 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()...' );
  }
}

mant-cert-certificacion.component.html:

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

This component, it's called from my router module. When i click on the "go back" button, i wish to display the previous component with their data loaded.

My route module:

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 { }

Some idea?

This previous component would be "XComponent". The content of the information (attributes or variables) does not matter. I only want to load their data please.

Thanks!

2 Answers2

2

If you want it to persist during navigation you go for

  1. LocalStorage
  2. sessionStorage
  3. Services

localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data.

I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular

For Angular 5:

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

Register it in your RootModule

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

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

Inject and use it

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

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

Usage

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

Vikas
  • 11,859
  • 7
  • 45
  • 69
-5

Angular preserves route details in its history.

window.history.back();

This should work.

Rakesh M R
  • 242
  • 2
  • 7