2

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?

Yogesh
  • 246
  • 1
  • 4
  • 20

1 Answers1

0

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);
      }
    });
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
  • Thanks for your help. So I will have to do this in all the 100+ components? Cant it be done in a shared service and just call the service when back button is pressed? – Yogesh Dec 18 '20 at 08:24
  • If you put last two codes in only app.component.ts it should work. Because all components comes from app.components. – mr. pc_coder Dec 18 '20 at 08:29