我有一个Angular应用程序,我想使用Google Analytics(分析)跟踪用户在每个页面上花费的时间。最好的方法是什么? (或者,也许还有Google Analytics(分析)的替代方法可以立即使用此功能?)
答案 0 :(得分:0)
由于Angular是SPA,因此您需要在Google Analytics(分析)上手动设置页面。为此,您需要在路由更改上设置一个侦听器。
需要与此类似的东西:
private subscribeToRouteChanges(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => this.sendPageDataToGoogleAnalytics(event.urlAfterRedirects));
}
public sendPageDataToGoogleAnalytics(url: string): void {
//need a title for each page which will be shown at GA dashboards
//you can setup your own service or static function to return a title for each route registered
const pageTitle = this.pageTitleService.getPageTitle(url);
if (pageTitle) {
(window as any).ga('set', 'page', url);
(window as any).ga('set', 'title', pageTitle);
(window as any).ga('send', 'pageview');
}
}