Angular integration

edit

This document covers how to use Real User Monitoring JavaScript agent with Angular applications.

Installing Elastic APM Angular package

edit

Install the @elastic/apm-rum-angular package as a dependency to your application:

npm install @elastic/apm-rum-angular --save

Instrumenting your Angular application

edit

The Angular integration package comes with a ApmService which uses Angular Depedency injection pattern and will start subscribing to Angular Router Events once the service is initialized.

ApmService must be initialized from either the application module or application component since the RUM agent has to start capturing all the resources and API calls as soon as possible.

import { NgModule, Inject } from '@angular/core'
import { Routes, Router, RouterModule } from '@angular/router'
import { ApmService } from '@elastic/apm-rum-angular'

const routes: Routes = [
  { path: 'contact', component: ContactListComponent },
  { path: 'contact/:id', component: ContactDetailComponent }
]

@NgModule({
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  declarations: [AppComponent, ContactListComponent, ContactDetailComponent],
  providers: [{
    provide: ApmService,
    useClass: ApmService,
    deps: [Router]
  }],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(@Inject(ApmService) service: ApmService) {
    // API is exposed through this apm instance
    const apm = service.init({
      serviceName: 'angular-app',
      serverUrl: 'http://localhost:8200'
    })

    apm.setUserContext({
      'username': 'foo',
      'id': 'bar'
    })
  }
}

Once the service is initialized, both page load and SPA navigation events will be captured as transactions with the path of the route as its name and page-load or route-change as type.

Capturing errors in Angular applications

edit

By default, when an error is thrown inside the Angular application, the default error handler prints the error messages to the console without rethrowing them as browser events.

ApmErrorHandler provides a centralized error handling which captures and reports the errors to be shown in the APM UI and also logs them to the browser console.

import { ErrorHandler } from '@angular/core'
import { ApmErrorHandler } from '@elastic/apm-rum-angular'

@NgModule({
  providers: [
    {
      provide: ErrorHandler,
      useClass: ApmErrorHandler
    }
  ]
})
class AppModule {}