Add platform service

This commit is contained in:
Giuseppe Digilio
2018-02-09 11:39:26 +01:00
parent e9acec0633
commit f91828a29a
2 changed files with 79 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
import { IPlatformService, PlatformService } from './platform.service'
import { async, TestBed } from '@angular/core/testing'
import { PLATFORM_ID } from '@angular/core'
describe('PlatformService', () => {
let service: IPlatformService;
describe('PlatformService browser', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
PlatformService,
{ provide: PLATFORM_ID, useValue: 'browser' }
]
})
}));
beforeEach(async(() => {
service = TestBed.get(PlatformService)
}));
afterEach(async(() => {
TestBed.resetTestingModule()
}));
it('should construct', async(() => {
expect(service).not.toBeNull()
}));
it('should be browser', async(() => {
expect(service.isBrowser).toEqual(true);
expect(service.isServer).toEqual(false)
}));
});
describe('PlatformService 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)
}))
})
});

View File

@@ -0,0 +1,20 @@
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)
}
}