feat(platform-server): add an API to transfer state from server (#19134)
TransferState provides a shared store that is transferred from the server to client. To use it import BrowserTransferStateModule from the client app module and ServerTransferStateModule from the server app module and TransferState will be available as an Injectable object. PR Close #19134
This commit is contained in:

committed by
Igor Minar

parent
f96142cd7c
commit
cfd9ca0d6f
42
packages/platform-server/src/transfer_state.ts
Normal file
42
packages/platform-server/src/transfer_state.ts
Normal file
@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {APP_ID, NgModule} from '@angular/core';
|
||||
import {DOCUMENT, TransferState, ɵescapeHtml as escapeHtml} from '@angular/platform-browser';
|
||||
|
||||
import {BEFORE_APP_SERIALIZED} from './tokens';
|
||||
|
||||
export function serializeTransferStateFactory(
|
||||
doc: Document, appId: string, transferStore: TransferState) {
|
||||
return () => {
|
||||
const script = doc.createElement('script');
|
||||
script.id = appId + '-state';
|
||||
script.setAttribute('type', 'application/json');
|
||||
script.textContent = escapeHtml(transferStore.toJson());
|
||||
doc.body.appendChild(script);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* NgModule to install on the server side while using the `TransferState` to transfer state from
|
||||
* server to client.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
@NgModule({
|
||||
providers: [
|
||||
TransferState, {
|
||||
provide: BEFORE_APP_SERIALIZED,
|
||||
useFactory: serializeTransferStateFactory,
|
||||
deps: [DOCUMENT, APP_ID, TransferState],
|
||||
multi: true,
|
||||
}
|
||||
]
|
||||
})
|
||||
export class ServerTransferStateModule {
|
||||
}
|
Reference in New Issue
Block a user