GriffinCodes
GriffinCodes

Reputation: 56

Programmatically hook into Angular lifecycle events

I am trying to report page load times to google analytics in my Angular 15 app. As far as I can tell, the only way to accurately measure the page load time is by using the AfterViewInit lifecycle hook. This works great, but I refuse to add it to all 100+ pages in the app, and I don't want to forget to add it to new pages in the future. So I would like to be able to subscribe to a components lifecycle hooks programmatically.

The best solutions I've found so far are @mixins and extending a base class, but again, I don't want to modify every page.

I am able to get a reference to the loaded component with the following code in my app's root component, I am hoping there is some library or utility I can use to then hook into the component's lifecycle.

this.router.events.pipe(
    tap((e: any) => {
        if (e instanceof ActivationEnd) {
            console.log("ActivationEnd", e.snapshot.component)
        }
    })
);

There might be a better way to achieve the same functionality. I've tried the following, but it only works on initial page load, and seems to be unreliable at best.

document.onreadystatechange = function () {
    console.log('document.readyState', document.readyState)
}

I've also tried using NgZone but it is reporting the page is fully loaded 10+ seconds after it appears to be.

Everything else I've tried (NavigationEnd, canActivateChild, etc) is firing far too early.

Upvotes: 2

Views: 94

Answers (0)

Related Questions