Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an angular 7 function after every on load page

Tags:

angular

Hy everone! Can anyone tell me how to invoke an angular 7 function after each page load?

like image 607
FedeLanza Avatar asked Jan 27 '23 10:01

FedeLanza


2 Answers

You can subscribe to the router events in the first page you load (usually app.components.ts) and check if the instance of the event is a NavigationEnd. To do so you can have to do this:

import { Router,NavigationEnd } from '@angular/router';

constructor(
   private router: Router
) {
   this.router.events.subscribe((e) => {
       if (e instanceof NavigationEnd) {
           // Function you want to call here
       }
    });
}

You have the live example here:

https://stackblitz.com/edit/angular-routing-function-stack-55723837?file=src/app/app.component.ts

like image 77
Daniel Piñeiro Avatar answered Jan 29 '23 01:01

Daniel Piñeiro


you can do that in the ngOnInit() method of the app component.

like image 42
Vasco Avatar answered Jan 29 '23 01:01

Vasco