Angular (v12) 检测浏览器触发的导航以发送 Google 分析调用
Angular (v12) detect browser triggered navigation to send Google analytics call
只有当我们从应用程序导航时,'ga' 在路由器事件中调用 app.component.ts
才有效,如果您直接在浏览器搜索栏中输入路径,则不会触发该事件。
app.component.ts
ngAfterViewInit() {
this.router.events.subscribe((event: any) => {
if(event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
})
}
像https://example.com/some-path
这样从浏览器直接导航到路径不会触发上述事件。
在每条路线中 'ga' 调用 ngOnInit()
是一种解决方案,但它是多余的。有什么有效的解决办法吗?
并且在 ngOnInit()
而不是 ngAfterViewInit()
中使用上述 GA 代码也无济于事。
以防万一有人遇到同样的问题,就像你做的时候在本地说的问题ng s
GA 在浏览器触发的导航上不起作用,但在生产服务器上,因为我们配置 nginx/apache 为了服务 angular 应用程序,我们将 404 页面重定向到应用程序的根目录,然后从那里 angular 处理到指定路由或 404 页面的重定向,这被视为应用程序导航和 GA 工作。
nginx 配置:
try_files $uri $uri/ /index.html;
只有当我们从应用程序导航时,'ga' 在路由器事件中调用 app.component.ts
才有效,如果您直接在浏览器搜索栏中输入路径,则不会触发该事件。
app.component.ts
ngAfterViewInit() {
this.router.events.subscribe((event: any) => {
if(event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
})
}
像https://example.com/some-path
这样从浏览器直接导航到路径不会触发上述事件。
在每条路线中 'ga' 调用 ngOnInit()
是一种解决方案,但它是多余的。有什么有效的解决办法吗?
并且在 ngOnInit()
而不是 ngAfterViewInit()
中使用上述 GA 代码也无济于事。
以防万一有人遇到同样的问题,就像你做的时候在本地说的问题ng s
GA 在浏览器触发的导航上不起作用,但在生产服务器上,因为我们配置 nginx/apache 为了服务 angular 应用程序,我们将 404 页面重定向到应用程序的根目录,然后从那里 angular 处理到指定路由或 404 页面的重定向,这被视为应用程序导航和 GA 工作。
nginx 配置:
try_files $uri $uri/ /index.html;