要在Angular Universal中集成Application Insights,可以按照以下步骤操作:
npm install @microsoft/applicationinsights-web
npm install @microsoft/applicationinsights-angular-web
app-insights.service.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { AppInsights } from 'applicationinsights-web';
@Injectable({
providedIn: 'root'
})
export class AppInsightsService {
private appInsights: AppInsights;
constructor() {
this.appInsights = new AppInsights({
config: {
instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE'
}
});
this.appInsights.loadAppInsights();
}
logPageView(name?: string, uri?: string) {
this.appInsights.trackPageView({
name,
uri
});
}
logEvent(name: string, properties?: { [key: string]: string }) {
this.appInsights.trackEvent({ name }, properties);
}
logException(exception: Error) {
this.appInsights.trackException({ exception });
}
}
请确保将YOUR_INSTRUMENTATION_KEY_GOES_HERE
替换为你自己的Instrumentation Key。
server.ts
文件中添加以下代码,以确保在服务器端启用Application Insights:import { enableProdMode } from '@angular/core';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppInsightsService } from './src/app/app-insights.service';
// ...
const app = express();
app.engine(
'html',
ngExpressEngine({
bootstrap: AppServerModule,
providers: [
// ...
{ provide: AppInsightsService, useClass: AppInsightsService }
]
})
);
// ...
确保将AppInsightsService
添加到providers
数组中。
app.module.ts
文件中添加以下代码,以确保在浏览器端启用Application Insights:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppInsightsService } from './app-insights.service';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'my-app' }),
],
providers: [
// ...
{
provide: AppInsightsService,
useClass: AppInsightsService
}
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(appInsightsService: AppInsightsService) {
if (environment.production) {
appInsightsService.logPageView(); // 记录初始页面视图
}
}
}
确保将AppInsightsService
添加到providers
数组中,并在构造函数中调用logPageView
方法以记录初始页面视图。
现在,你可以在任何需要的地方注入AppInsightsService
,并使用它来记录页面视图、事件和异常。例如,在组件中的某个方法中添加以下代码:
import { Component } from '@angular/core';
import { AppInsightsService } from './app-insights.service';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
constructor(private appInsightsService: AppInsightsService) {}
logEvent() {
this.appInsightsService.logEvent('Button Click', { buttonName: 'Log Event' });
}
logException() {
try {
throw new Error('An error occurred');
} catch (error) {
this.appInsightsService.logException(error);
}
}
}
这样,Angular Universal中的Application Insights集成就完成了。你可以根据需要在其他地方使用AppInsightsService
来记录更多的页面视图、事件和异常。