简体   繁体   中英

Hard reload a page when back button is pressed in Angular

I have an Angular 8 app with more than 100 pages ( components ) and am only using the application for Chrome browser. Randomly the CSS gets distorted when I click the browser back button and I have to to a Ctrl + Shift + R to get the CSS to load correctly. So I am looking for a way to so this automatically whenever the browser Back button is pressed.

So basically looking to do a "Hard Re-Load" when the user clicks on the browser Back button on any of the pages so that user goes back to the previous page and "Ctrl + Shift + R" is auto done. Is there an Angular way to do this for all the pages. I looked at:

How to force reloading a page when using browser back button?

but not sure how to implement it in Angular and apply it to all pages. Any help?

You can use one generic service to communicate between components.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class BackServiceService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject(false);// inside bracket you can send any type
  sharedData = this.paramSource.asObservable();
  setParam(param:boolean) { this.paramSource.next(param)}    
}

in components with hostlistener you can listen if back button clicked then change service value

 @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    console.log('Back button pressed');
    this.back.setParam(true);
  }

in component u came back you can check service value and

this.back.sharedData.subscribe(result => {
      console.log(result);
      if (result) {
        window.location.reload(true);
        this.back.setParam(false);
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM