Last active
October 14, 2017 00:21
-
-
Save MarkPieszak/53c9794540faaac4211de1a50418ad8f to your computer and use it in GitHub Desktop.
Angular Universal - Window service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app.module.ts | |
export function win () { | |
return typeof window !== 'undefined' ? window : {}; | |
} | |
// ... in the NgModule | |
{ provide: WindowService, useFactory: (win) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @NgModule providers[] | |
{ provide: WindowService, useClass: WindowService } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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