Created
July 8, 2018 20:29
-
-
Save arutnik/67b11fc65f99ef8b41f34f95d7f1f955 to your computer and use it in GitHub Desktop.
SEO-SPA: Transfer State
This file contains hidden or 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 { Injectable, Inject, PLATFORM_ID } from '@angular/core'; | |
import { TransferState, makeStateKey } from '@angular/platform-browser'; | |
import { isPlatformServer } from '@angular/common'; | |
/** | |
* A service that when injected in the app component | |
* will print a version injected by the server | |
* once loaded on the client | |
*/ | |
@Injectable() | |
export class VersionPrinterService { | |
constructor(private transferState: TransferState, | |
@Inject(PLATFORM_ID) private platformId: Object) | |
{ | |
this.printVersionNumber(); | |
} | |
private printVersionNumber() { | |
let key = makeStateKey<String>('APP_VERSION'); | |
let versionFromServer = this.transferState.get(key, ''); | |
if (versionFromServer) { | |
console.log("Rendered from version: " + versionFromServer); | |
} else if (isPlatformServer(this.platformId)) { | |
// If the key is not in the cache we are most likely running | |
// on server, but we'll check anyway in case server | |
// rendering is being bypassed somehow | |
// Get a version number from an env variable, | |
// store it in the serialized document via TransferState | |
this.transferState.set(key, process.env.APP_VERSION); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment