Search code examples
angulargoogle-analyticsangular-router

How to report current title to Google Analytics from angular?


I have successfully reported the URL of the current page to Google Analytics, but it is reporting the previous page's title.

I have looked at several tutorials, and none of them discuss the page title.

Here is the code in my app.component.ts file that I am using:

constructor(public router: Router) {
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            // FIXME need to make this track the correct current title.
            gtag('config', 'UA-XXXXXXXXX-X', {
                page_path: event.urlAfterRedirects
            });
        }
    });
}

I would expect it to report the title that I set after the constructor for the page has run, but it seems to be sending the previous one. My title is generated based on data from a subscription if that provides any useful context.


Solution

  • Try to set the same logic in ngOninit, as constructor is not a place to set or get properties.

     export class App implements OnInit{ 
          constructor(){
             //called first time before the ngOnInit()
           }
    
       ngOnInit(){
           //called after the constructor and called  after the first ngOnChanges() 
        }
     }