# Angular

### ⚙️ Integration

To collect errors and crashes in your Angular application, run the following command in the terminal at the root of your project to install [bugsplat-ng](https://github.com/BugSplat-Git/bugsplat-ng):

```bash
npm i bugsplat-ng --save
```

Add a `database` property in your package.json that corresponds to your BugSplat database:

```json
{
  "database": "your_bugsplat_database"
}
```

Add values for your BugSplat `database`, `application`, and `version` to your application's environment files.

[environment.prod.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/8c12d9b3544f2b618491467e6c40d84b6139eb2a/src/environments/environment.prod.ts#L1)

```javascript
const packageJson = require('../../package.json');
export const environment = {
  production: true,
  bugsplat: {
    database: packageJson.database,
    application: packageJson.name,
    version: packageJson.version
  }
};
```

For Angular applications using standalone components, import and configure BugSplat directly in your `main.ts` file:

[main.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/22fa88dc642294f1a6240a0a1bf4b4acd16f727d/projects/my-angular-crasher/src/main.ts#L6-L29)

```typescript
import { BugSplatModule } from 'bugsplat-ng';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(
      BugSplatModule.initializeApp(environment.bugsplat)
    )
  ]
})
.catch(err => console.log(err));
```

Alternatively, add an import for `BugSplatModule` to your `AppModule`:

```typescript
import { BugSplatModule } from 'bugsplat-ng';

@NgModule({
  imports: [
    BugSplatModule.initializeApp(environment.bugsplat)
  ]
})
```

Throw a new error in your application to test the bugsplat-ng integration:

[app.component.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/8c12d9b3544f2b618491467e6c40d84b6139eb2a/src/app/app.component.ts#L37)

```typescript
throw new Error("foobar!");
```

Navigate to the [Crashes](https://app.bugsplat.com/v2/crashes) page in BugSplat, and you should see a new crash report for the application you just configured. Click the link in the ID column to see details about your crash on the Crash page:

<figure><img src="https://976110677-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LBMgmIcgkIXSUfnXDSv%2Fuploads%2FHM6PC096udwXz5w071lJ%2Fimage.png?alt=media&#x26;token=fbe6d06c-15c5-42d6-a635-fcca79ecaf48" alt=""><figcaption></figcaption></figure>

<figure><img src="https://976110677-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LBMgmIcgkIXSUfnXDSv%2Fuploads%2FscS0fNmPKQ3XFOtzXYCC%2Fimage.png?alt=media&#x26;token=e3a55656-36e3-4537-80a3-d9a14f6c3573" alt=""><figcaption></figcaption></figure>

### 🗺 Source Maps

BugSplat supports unwinding uglified and minified JavaScript stack traces via source maps. To upload source maps to BugSplat during your build, install [@bugsplat/symbol-upload](https://www.npmjs.com/package/@bugsplat/symbol-upload).

```bash
npm i -D @bugsplat/symbol-upload
```

Configure your `angular.json` file to output source maps. We suggest enabling source maps for both your application code and any vendor chunks generated by Angular.

```json
{
  "projects": {
    "main": {
      "architect": {
        "build": {
          "options": {
            "sourceMap": {
              "scripts": true,
              "styles": true,
              "vendor": true
            },
          },
        }
      }
    }
  }
}
```

Add `SYMBOL_UPLOAD_CLIENT_ID` and `SYMBOL_UPLOAD_CLIENT_SECRET` environment variables for the BugSplat user that you will use to upload symbols. You can create these values as system environment variables or use [dotenv](https://www.npmjs.com/package/dotenv).

```
SYMBOL_UPLOAD_CLIENT_ID=your-client-id
SYMBOL_UPLOAD_PASSWORD=your-client-secret
```

Add a script to `package.json` that reads a `.env` file and calls `symbol-upload` to upload source maps after your production build. Replace `my-angular-crasher` with the name of your Angular project.

```json
{
  "scripts": {
    "postbuild": "node -r dotenv/config ./node_modules/@bugsplat/symbol-upload/dist/bin/index.js -d ./dist/my-angular-crasher/browser"
  }
}
```

For best results, please upload source maps for every released version of your application.

### 🧰 Extended Integration

You can post additional information by creating a service that implements ErrorHandler. In the `handlerError` method, make a call to `BugSplat.post` passing it the error and an optional options object:

[my-angular-error-handler.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/master/src/app/my-angular-error-handler.ts)

```
import { ErrorHandler, Injectable } from '@angular/core';
import { BugSplat } from 'bugsplat-ng';

@Injectable()
export class MyAngularErrorHandler implements ErrorHandler {

    constructor(public bugsplat: BugSplat) { }
    
    async handleError(error: Error): Promise<void> {
        return this.bugsplat.post(error, {
            description: 'New description from MyAngularErrorHandler.ts'
        });
    }
}
```

BugSplat provides the following properties and methods that allow you to customize its functionality:

[bugsplat.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/master/projects/bugsplat-ng/src/lib/bugsplat.ts)

```
BugSplat.description: string; // Additional info about your crash that gets reset after every post
BugSplat.email: string; // The email of your user 
BugSplat.key: string; // A unique identifier for your application
BugSplat.user: string; // The name or id of your user
BugSplat.files: Array<file>; // A list of files to be uploaded at post time
BugSplat.getObservable(): Observable<BugSplatPostEvent>; // Observable that emits BugSplat crash post events results in your components.
async BugSplat.post(error): Promise<void>; // Post an Error object to BugSplat manually from within a try/catch
```

In either `bootstrapApplication` or `NgModule`, add a provider for your new `ErrorHandler`:

[main.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/22fa88dc642294f1a6240a0a1bf4b4acd16f727d/projects/my-angular-crasher/src/main.ts#L6-L29)

```typescript
import { BugSplatModule } from 'bugsplat-ng';
import { MyAngularErrorHandler } from './app/my-angular-error-handler';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(
      BugSplatModule.initializeApp(environment.bugsplat)
    ),
    {
      provide: ErrorHandler,
      useClass: MyAngularErrorHandler
    }
  ]
})
.catch(err => console.log(err));
```

You can also configure BugSplat's logging preferences and provide your own logging implementation. Create a provider for BugSplatLogger with useValue set to a new instance of BugSplatLogger. Pass one of the BugSplatLogLevel options as the first parameter to BugSplatLogger. You can provide an instance of your own custom logger as the second parameter granted it has an error, warn, info, and log methods. If no custom logger is provided, the console will be used:

[main.ts](https://github.com/BugSplat-Git/bugsplat-ng/blob/22fa88dc642294f1a6240a0a1bf4b4acd16f727d/projects/my-angular-crasher/src/main.ts#L6-L29)

```typescript
import { BugSplatLogger, BugSplatLogLevel, BugSplatModule } from 'bugsplat-ng';
import { MyAngularErrorHandler } from './app/my-angular-error-handler';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(
      BugSplatModule.initializeApp(environment.bugsplat)
    ),
    {
      provide: ErrorHandler,
      useClass: MyAngularErrorHandler
    },
    {
      provide: BugSplatLogger,
      useValue: new BugSplatLogger(BugSplatLogLevel.Log)
    }
  ]
})
.catch(err => console.log(err));
```

### 💬 User Feedback

In addition to crash reporting, BugSplat supports collecting non-crashing user feedback such as bug reports and feature requests. Feedback reports appear in BugSplat with the "User Feedback" type, grouped by title.

Inject the `BugSplat` service and call `postFeedback`:

```typescript
import { Component } from '@angular/core';
import { BugSplat } from 'bugsplat-ng';

@Component({ ... })
export class FeedbackComponent {
  constructor(private bugsplat: BugSplat) {}

  async submitFeedback() {
    await this.bugsplat.postFeedback('Login button broken', {
      description: 'Nothing happens when I tap it',
      email: 'jane@example.com',
    });
  }
}
```

You can also attach files such as screenshots:

```typescript
async submitWithScreenshot(file: File) {
  await this.bugsplat.postFeedback('UI rendering issue', {
    description: 'The sidebar overlaps the main content.',
    attachments: [
      { filename: file.name, data: file },
    ],
  });
}
```

### 🧑‍🏫 Sample

This repository includes a sample `my-angular-crasher` application that has been pre-configured with BugSplat. Get started by cloning the repository and navigating to the root of the project:

```bash
git clone https://github.com/BugSplat-Git/bugsplat-ng
cd bugsplat-ng
```

Before you can run the app, you'll need to create an OAuth2 Client ID & Client Secret pair that corresponds to your BugSplat database, as shown [here](https://docs.bugsplat.com/introduction/development/web-services/oauth2). Please also take note of the BugSplat `database` that this OAuth2 Client ID & Client Secret pair corresponds to.

First, add a `database` property in your package.json that corresponds to your BugSplat database:

```json
{
  "database": "your_bugsplat_database"
}
```

Next, create a [dotenv](https://github.com/motdotla/dotenv) file with the name `.env` at the root of the repository and populate it with the correct values substituted for `your-client-id` and `your-client-secret`:

```
SYMBOL_UPLOAD_CLIENT_ID=your-client-id
SYMBOL_UPLOAD_CLIENT_SECRET=your-client-secret
```

To start the sample app, run `npm start` in the root of the repository.

```
npm start
```

The `npm start` command will build the sample application and upload [source maps](https://docs.bugsplat.com/introduction/development/working-with-symbol-files/source-maps) to BugSplat so that the JavaScript call stack can be mapped back to TypeScript. Once the build has completed, the source maps will be uploaded and `http-server` will serve the app.

Navigate to the URL displayed in the console by `http-server` (usually [localhost:8080](http://127.0.0.1:8080/)). Click any button in the sample app to generate an error report. A link to the error report should display in the app shortly after clicking a button. Click the link to the error report, and when prompted, log in to BugSplat.

If everything worked correctly, you should see information about your error as well as a TypeScript stack trace.

### 🧑‍💻 Contributing

BugSplat loves open-source software! If you have suggestions on how we can improve this integration, please reach out to <support@bugsplat.com>, create an [issue](https://github.com/BugSplat-Git/bugsplat-ng/issues) in our [GitHub repo](https://github.com/BugSplat-Git/bugsplat-ng) or send us a [pull request](https://github.com/BugSplat-Git/bugsplat-ng/pulls).

With ❤️,

The BugSplat Team
