same Question here... found Solution to share:
(First Stackoverflow contribution, excuse form issues)
- Look at existing Providers
I've looked at this one cause its quite simple.
- Rename it to fit your needs
- Remove strange
declare var _kmq: any;
and inject your own ApiService instead.
- Track your Stuff
I've removed this.angulartics2.setUsername
and this.angulartics2.setUserProperties
from constructor. Cause I don't know what it is used for...
My backend Team provided an endpoint which awaits following data structure:
export interface AnalyticsDataInterface {
id?: number;
userId: number;
action: AnalyticsAction|string;
properties: string[];
date: string;
}
My Analytics Actions so far:
export enum AnalyticsAction {
PAGE_VIEW = 'page_view',
LOGIN = 'login_success',
}
Then this would be my ApiService:
@Injectable({
providedIn: 'root'
})
export class AnalyticsService extends ApiService{
public sendData(data: AnalyticsDataInterface){
this.post<AnalyticsDataInterface>(Endpoint.ANALYTICS, data).subscribe();
}
}
And last but not least my CustomProvider:
@Injectable({ providedIn: 'root' })
export class AngularticsProvider {
constructor(
private angulartics2: Angulartics2,
private api: AnalyticsService,
private userService: UserService
) {
// this.angulartics2.setUsername
// .subscribe((x: string) => this.setUsername(x));
// this.angulartics2.setUserProperties
// .subscribe((x) => this.setUserProperties(x));
}
startTracking(): void {
this.angulartics2.pageTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.pageTrack(x.path));
this.angulartics2.eventTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.eventTrack(x.action, x.properties));
}
pageTrack(path: string) {
const requestData: AnalyticsDataInterface = {
userId: this.userService.getUser().id,
action: AnalyticsAction.PAGE_VIEW,
properties: [path],
date: new Date().toISOString()
};
this.api.sendData(requestData);
}
eventTrack(action: string, properties: string[]) {
const requestData: AnalyticsDataInterface = {
userId: this.userService.getUser().id,
action,
properties,
date: new Date().toISOString()
};
this.api.sendData(requestData);
}
}
Then just follow normal installation instructions
import Angulartic2Module to AppModule:
imports: [
...
Angulartics2Module.forRoot(),
...
]
inject your custom provider service to AppComponent and start tracking:
export class AppComponent implements OnInit {
constructor(
private myCustomProvider: AngularticsProvider
) {
myCustomProvider.startTracking();
}
}
The rest should be default...