Skip to content

Commit

Permalink
fix(core): only try to retrieve transferred state on the browser
Browse files Browse the repository at this point in the history
Prior to this commit we tried to retrieve transferred state on both browser and server. Doing this on the server was redundant and could causes issues as `document` might be undefined.

Closes angular#50138
  • Loading branch information
alan-agius4 committed May 4, 2023
1 parent 2419c48 commit f73458c
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions packages/core/src/transfer_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {APP_ID} from './application_tokens';
import {APP_ID, PLATFORM_ID} from './application_tokens';
import {inject} from './di/injector_compatibility';
import {ɵɵdefineInjectable} from './di/interface/defs';
import {getDocument} from './render3/interfaces/document';
Expand Down Expand Up @@ -72,7 +72,10 @@ export function makeStateKey<T = void>(key: string): StateKey<T> {

function initTransferState() {
const transferState = new TransferState();
transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
if (inject(PLATFORM_ID) === 'browser') {
transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
}

return transferState;
}

Expand Down Expand Up @@ -165,18 +168,18 @@ export class TransferState {
}
}

function retrieveTransferredState(doc: Document, appId: string) {
function retrieveTransferredState(doc: Document, appId: string): {[k: string]: unknown|undefined} {
// Locate the script tag with the JSON data transferred from the server.
// The id of the script tag is set to the Angular appId + 'state'.
const script = doc.getElementById(appId + '-state');
let initialState = {};
if (script && script.textContent) {
if (script?.textContent) {
try {
// Avoid using any here as it triggers lint errors in google3 (any is not allowed).
initialState = JSON.parse(unescapeTransferStateContent(script.textContent)) as {};
return JSON.parse(unescapeTransferStateContent(script.textContent)) as {};
} catch (e) {
console.warn('Exception while restoring TransferState for app ' + appId, e);
}
}
return initialState;

return {};
}

0 comments on commit f73458c

Please sign in to comment.