Skip to content

Instantly share code, notes, and snippets.

@MarkPieszak
Last active October 14, 2017 00:21
Show Gist options
  • Save MarkPieszak/53c9794540faaac4211de1a50418ad8f to your computer and use it in GitHub Desktop.
Save MarkPieszak/53c9794540faaac4211de1a50418ad8f to your computer and use it in GitHub Desktop.
Angular Universal - Window service
// app.module.ts
export function win () {
return typeof window !== 'undefined' ? window : {};
}
// ... in the NgModule
{ provide: WindowService, useFactory: (win) }
// @NgModule providers[]
{ provide: WindowService, useClass: WindowService }
import { Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
constructor(
private window: WindowService,
@Inject(PLATFORM_ID) private platformId: Object
) {
if (isPlatformBrowser(this.platformId)) {
(<any>this.windowService).$('body')... // something crazy involving the window
}
}
@Injectable()
export class WindowService {
// Some typical window use-cases
public navigator: any = {};
public location: any = {};
// google tag manager stub for web
public dataLayer: Array<any> = [];
public alert(msg: string) { return; }
public confirm(msg: string) { return; }
public btoa(msg: string): string { return null; }
public scrollTo(a: number, b: number) { return null; }
public open(...args: Array<any>): any { return null; }
public setTimeout(handler: (...args: any[]) => void, timeout?: number): number { return 0; }
public clearTimeout(timeoutId: number): void { }
public setInterval(handler: (...args: any[]) => void, ms?: number, ...args: any[]): number { return 0; }
public clearInterval(intervalId: number): void { }
// google analytics stub for web
public ga(command: string | Function, params?: any, extra?: any): void { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment