Search code examples
angularaudiocontextbrowser-api

ReferenceError: AudioContext is not defined in Angular service


In my Angular service, I have defined AudioContext, like so:

@Injectable({
  providedIn: 'root'
})
export class AudioService {
    private context = new AudioContext();

    ...
}

At compile time, Angular throws:

ReferenceError: AudioContext is not defined

But I can do it from the developer console without complaint (this works):

const context = new AudioContext();

It appears that quite a lot (possibly all) of the dom APIs don't seem to be available at compile-time; for example, I tried new Image() and new XMLHttpRequest()

For reference, I'm using:

  • Chrome 122
  • Angular 17

My tsconfig.json file lists the following libs:

{
  "lib": [
    "ES2022",
    "dom"
  ]
}

How do I get Angular to play nicely with Browser APIs?


Solution

  • You're are probably running your app with SSR enabled.

    SSR is run in a node environment that doesn't support browser APIs.

    If you need to run browser code, you can wrap it with

    afterNextRender(() => {
      const ctx = new AudioContext();
      // ...
    })