文章内容
2020/6/6 17:57:15,作 者: 黄兵
在Angular中使用Google Analytics
最近项目进入后期的一些调试阶段,需要统计访客量,使用的是Google Analytics,在Angular中只需要写一个服务,具体内容如下:
import {Injectable} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
import {environment} from '../../environments/environment.prod';
import {LogService} from './log.service';
// tslint:disable-next-line:ban-types
declare var gtag: Function;
@Injectable({
providedIn: 'root'
})
export class AnalyticsService {
constructor(private router: Router,
private _logService: LogService) {
}
public event(eventName: string, params: {}) {
gtag('event', eventName, params);
}
public init() {
this.listenForRouteChanges();
try {
const script1 = document.createElement('script');
script1.async = true;
script1.src = 'https://www.googletagmanager.com/gtag/js?id=' + environment.googleAnalyticsKey;
document.head.appendChild(script1);
const script2 = document.createElement('script');
script2.innerHTML = `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '` + environment.googleAnalyticsKey + `', {'send_page_view': false});
`;
document.head.appendChild(script2);
} catch (ex) {
console.error('Error appending google analytics');
this._logService.error(`error_message: ${ex}`, 'function:init()', 'AnalyticsService error.');
}
}
private listenForRouteChanges() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
gtag('config', environment.googleAnalyticsKey, {
page_path: event.urlAfterRedirects,
});
}
});
}
}
这里使用的是providedIn注入方式,这个是在Angular 6中新增的功能,关于此详细信息,可以参考这篇文章:Total Guide To Angular 6+ Dependency Injection — providedIn vs providers:[ ]
在每个要监控的页面,注入服务,像这样:
@Component({
selector: 'app-template-notice',
templateUrl: './template_notice.component.html',
styleUrls: ['./template_notice.component.scss']
})
export class TemplateNoticeComponent implements OnInit {
errorMessages: any[] = [];
constructor(private _analytics: AnalyticsService) {
}
ngOnInit() {
// google analytics
this._analytics.init();
}
}
在environment.prod.ts,将Analytics ID添加为 googleAnalyticsKey: 'UA-XXXXXXX-XXXX'
像这样:
export const environment = {
production: true,
googleAnalyticsKey: 'UA-1099xxx55-5'
};
好了,使用Google Analytics监控应用程序就完成了。
参考资料:
1、Angular 4+ using Google Analytics
2、Total Guide To Angular 6+ Dependency Injection — providedIn vs providers:[ ]
2、在线案例(ProvidedIn):stackblitz - angular-providedin
黄兵个人博客原创。
评论列表