首页 > 解决方案 > 如何从角度向 Google Analytics 报告当前标题?

问题描述

我已成功将当前页面的 URL 报告给 Google Analytics,但它正在报告上一页的标题。

我看过几个教程,但没有一个讨论页面标题。

这是app.component.ts我正在使用的文件中的代码:

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
            });
        }
    });
}

我希望它报告我在页面的构造函数运行后设置的标题,但它似乎正在发送前一个标题。如果订阅提供任何有用的上下文,我的标题是根据订阅数据生成的。

标签: angulargoogle-analyticsangular-router

解决方案


尝试在 ngOninit 中设置相同的逻辑,因为构造函数不是设置或获取属性的地方。

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

   ngOnInit(){
       //called after the constructor and called  after the first ngOnChanges() 
    }
 }

推荐阅读