SerMarvz
SerMarvz

Reputation: 163

Angular Router Event

Tried to use some applicationinsights service found in github https://github.com/sandorfr/ngx-app-insights-sample/issues/1 but it seems the service is encountering error

Tried to import some event as recommended in stackoverflow

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, ResolveEnd, ActivatedRouteSnapshot } from '@angular/router';
import { Subscription } from 'rxjs';
import 'rxjs/add/operator/filter';
import { AppInsights } from 'applicationinsights-js';
import { NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
const environment = {
    production: false,
    appInsights: {
        instrumentationKey: 'sampleinstrumentationkey'
    }
};
@Injectable()
export class MonitoringService {

    private routerSubscription: Subscription;

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) {
        if (environment.appInsights && environment.appInsights.instrumentationKey) {
            if (AppInsights.downloadAndSetup) {
                AppInsights.downloadAndSetup(environment.appInsights);
            }
        }
        router.events.pipe(
            filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
            const activatedComponent = this.getActivatedComponent(router.routerState.snapshot.root);
            if (activatedComponent) {
                this.logPageView(`${activatedComponent.name} ${this.getRouteTemplate(router.routerState.snapshot.root)}`, event.urlAfterRedirects);
            }
        });
    }

    setAuthenticatedUserId(userId: string): void {
        AppInsights.setAuthenticatedUserContext(userId);
    }

    private getActivatedComponent(snapshot: ActivatedRouteSnapshot): any {

        if (snapshot.firstChild) {
            return this.getActivatedComponent(snapshot.firstChild);
        }

        return snapshot.component;
    }

    private getRouteTemplate(snapshot: ActivatedRouteSnapshot): string {
        let path = '';
        if (snapshot.routeConfig) {
            path += snapshot.routeConfig.path;
        }

        if (snapshot.firstChild) {
            return path + this.getRouteTemplate(snapshot.firstChild);
        }

        return path;
    }

    private AddGlobalProperties(properties?: { [key: string]: string }): { [key: string]: string } {
        if (!properties) {
            properties = {};
        }

        //add your custom properties such as app version

        return properties;
    }

    public logPageView(
        name: string,
        url?: string,
        properties?: { [key: string]: string },
        measurements?: { [key: string]: number },
        duration?: number) {

        AppInsights.trackPageView(name, url, this.AddGlobalProperties(properties), measurements, duration);
    }

    public logEvent(name: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) {
        AppInsights.trackEvent(name, this.AddGlobalProperties(properties), measurements);
    }

    public logError(error: Error, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) {
        AppInsights.trackException(error, undefined, this.AddGlobalProperties(properties), measurements);
    }
}

the code is working but in a certain amount of time i encounter the following error

ERROR in [at-loader] ./ClientApp/app/components/services/app-insights/app-insights.service.ts:30:21

TS2345: Argument of type '(event: NavigationEnd) => void' is not assignable to parameter of type '((value: Event) => void) | undefined'. Type '(event: NavigationEnd) => void' is not assignable to type '(value: Event) => void'. Types of parameters 'event' and 'value' are incompatible. Type 'Event' is not assignable to type 'NavigationEnd'. Type 'RouterEvent' is not assignable to type 'NavigationEnd'. Property 'urlAfterRedirects' is missing in type 'RouterEvent'.

Upvotes: 1

Views: 2068

Answers (1)

Rob
Rob

Reputation: 3746

I believe that telling Typescript that the filter operator will ensure that event is of type NavigationEnd will solve that error:

        router.events.pipe(
            filter((event: Event): event is NavigationEnd => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {

You will need to import those types:

import { Event, NavigationEnd } from '@angular/router';

Upvotes: 6

Related Questions