I want to detect when page is refresh using router in my single page application (Angular project)
Is there any alternate way?
There isn't any default way to respond to this inside your Angular application. You might be able to mock something up using onBeforeUnload() to log that the application was reloaded; and then check that log in your application's initialization routine to perform some special action.
When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser.
On reload, your angularJS app will rerun it's initializations, but the code itself may be cached to your browser.
You cannot prevent page refresh. The browser user can always hit F5. The "onbeforeunload" approach will allow you to warn the user, but you can't prevent it.
In the component.ts
import { Subscription } from 'rxjs';
export let browserRefresh = false;
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnDestroy {
subscription: Subscription;
constructor(private router: Router) {
this.subscription = router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
browserRefresh = !router.navigated;
}
});
}
in the page you need
import { browserRefresh } from '../app.component';
....
ngOnInit() {
this.browserRefresh = browserRefresh;
console.log('refreshed?:', browserRefresh);
}
See working example here https://stackblitz.com/edit/refreshangular?file=src%2Fapp%2Fpage-a%2Fpage-a.component.ts
Click on page A & Page B & refresh to see the difference
try this
this.router.events
.pipe(filter((rs): rs is NavigationEnd => rs instanceof NavigationEnd))
.subscribe(event => {
if (
event.id === 1 &&
event.url === event.urlAfterRedirects
) {
..... // here your code when page is refresh
}
})
You will need to import
import { filter } from 'rxjs/operators'
import { Router } from '@angular/router';
An Angular application is a single page application, and in the context of a single page application the full app is loaded once, and data or screens are refreshed as the user uses your application.
A browser refresh is the equivalent of shutting down your application and launching it again. There is no default way to respond to this inside your Angular application.
You might be able to mock something up using onBeforeUnload() to log that the application was reloaded; and then check that log in your application's initialization routine to perform some special action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With