I want to detect when a page is refreshed using a router in my single-page application (Angular project).
Is there an alternate way?
I want to detect when a page is refreshed using a router in my single-page application (Angular project).
Is there an alternate way?
In the component.ts file:
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 a working example at https://stackblitz.com/edit/refreshangular?file=src%2Fapp%2Fpage-a%2Fpage-a.component.ts
Click on page A and 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
) {
// Your code here for when the page is refreshd
}
})
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 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.
The newest way in Angular 7 and later is that we can now add route navigation properties.
So if /somepage
is the page we want to detect and if the browser was refreshed, we set the navigate property prevPage when we go to this page:
this.router.navigate(['/somepage'], { state: { prevPage: this.router.url } });
Then inside somepage:
ngOnInit(): void {
const previousUrl = history.state.prevPage ?? null;
if (!this.previousUrl) {
console.log('page was refreshed!');
} else {
console.log('I came here from: ', previousUrl);
}
}
Note: This works if you want to detect browser refresh from a specific page.
If you need this throughout the site then I would go with a different approach.
I want to detect when page is refresh using router
You add a top level resolver to the router. If you have a single top level router, then it will only be resolved once and children will handle page navigation. Each time the resolver is resolved is equal to a page refresh in the browser.
const routes: Routes = [
{
path: '',
component: TopComponent,
resolve: { loaded: PageLoadedResolver },
children: [
...
]
}
];
There are many other ways of detecting a page load event in Angular.
The constructor of your AppModule
.
@NgModule({...})
export class AppModule {
public constructor() {
console.log('page loaded');
}
}
A service injected into the root that is used at least once.
@Injector({provideIn: 'root'})
export class MyService {
public constructor() {
console.log('page loaded');
}
}
There is also the main.ts
file which bootstraps the Angular application.
platformBrowserDynamic().bootstrapModule(AppModule)
.then(() => console.log('page loaded'))
.catch(err => console.error(err));
Basically, anywhere there is JavaScript that runs once...