Angular Platform Service

When working with any non-browser Angular runtime environments like Angular Universal (NativeScript, etc), it is useful to create a server layer for determing which environment the user is on. The code below demonstrates a simple way to implement such a service in an a universal environment. Becuase DOM heavy code cannot usually be executed on the server, we can create a conditional to ensure we are in the browser environment before executing browser only code (and vice-versa)

import { Inject, Injectable, PLATFORM_ID } from '@angular/core'
import { isPlatformBrowser, isPlatformServer } from '@angular/common'

export interface IPlatformService {
  readonly isBrowser: boolean
  readonly isServer: boolean
}
 
@Injectable()
export class PlatformService implements IPlatformService {
  constructor( @Inject(PLATFORM_ID) private platformId: any) { }
 
  public get isBrowser(): boolean {
    return isPlatformBrowser(this.platformId)
  }
 
  public get isServer(): boolean {
    return isPlatformServer(this.platformId)
  }
}

with the accompanying unit tests

import { IPlatformService, PlatformService } from './platform.service'
import { async, TestBed } from '@angular/core/testing'
import { PLATFORM_ID } from '@angular/core'

describe(PlatformService.name, () => {
  let service: IPlatformService

  describe(`${PlatformService.name}.browser`, () => {
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        providers: [
          PlatformService,
          { provide: PLATFORM_ID, useValue: 'browser' }
        ]
      })
    }))

    beforeEach(async(() => {
      service = TestBed.get(PlatformService)
    }))

    afterEach(async(() => {
      TestBed.resetTestingModule()
    }))

    it('should be browser', async(() => {
      expect(service.isBrowser).toEqual(true)
      expect(service.isServer).toEqual(false)
    }))
  })

  describe(`${PlatformService.name}.server`, () => {
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        providers: [
          PlatformService,
          { provide: PLATFORM_ID, useValue: 'server' }
        ]
      })
    }))

    beforeEach(async(() => {
      service = TestBed.get(PlatformService)
    }))

    afterEach(async(() => {
      TestBed.resetTestingModule()
    }))

    it('should be server', async(() => {
      expect(service.isServer).toEqual(true)
      expect(service.isBrowser).toEqual(false)
    }))
  })
})