import { Component } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';
import { TransferState, StateKey, makeStateKey } from '@angular/platform-browser';

const stateKey: StateKey<string> = makeStateKey('AppComponent');

@Component({
    selector: 'app',
    template: '<p>{{text}}</p>',
})
export class AppComponent {
    text: string;

    constructor(
        @Inject(PLATFORM_ID) platformId: Object,
        transferState: TransferState
    ) {
        if (isPlatformServer(platformId)) {
            this.text = "Hello from server";
            transferState.onSerialize(stateKey, () => "42");
        } else {
            const payload: string = transferState.get(stateKey, "Not found!");
            this.text = `Hello from client. Payload from server: ${payload}`;
            transferState.remove(stateKey);
        }
    }
}
