Skip to content
This repository was archived by the owner on Apr 8, 2020. It is now read-only.

Accessing globals from boot-server prerendering #903

Closed
abhilash1990 opened this issue Apr 28, 2017 · 4 comments
Closed

Accessing globals from boot-server prerendering #903

abhilash1990 opened this issue Apr 28, 2017 · 4 comments

Comments

@abhilash1990
Copy link

abhilash1990 commented Apr 28, 2017

Hello Steve,

I am using the Angular2Spa template and below is my boot-server.ts

import 'angular2-universal-polyfills';
import 'zone.js';
import { enableProdMode } from '@angular/core';
import { platformNodeDynamic } from 'angular2-universal';
import { AppModule } from './app/app.module';

enableProdMode();
const platform = platformNodeDynamic();

export default function (params: any): Promise<{ html: string, globals?: any }> {
return new Promise((resolve, reject) => {
const requestZone = Zone.current.fork({
name: 'angular-universal request',
properties: {
baseUrl: '/',
requestUrl: params.url,
originUrl: params.origin,
preboot: false,
// TODO: Render just the component instead of wrapping it inside an extra HTML document
// Waiting on angular/universal#347
document: ''
},
onHandleError: (parentZone, currentZone, targetZone, error) => {
// If any error occurs while rendering the module, reject the whole operation
reject(error);
return true;
}
});

return requestZone.run<Promise>(() => platform.serializeModule(AppModule)).then(html => {
resolve({
html: html,
globals: { myKey: params.data.myVal }
});
}, reject);
});
}

And inside the app component constructor i am trying to access like below

constructor(){
const data= (window as any).myKey;
}

Inside Index.cshtml

asp-ng2-prerender-module="ClientApp/dist/main-server"
asp-ng2-prerender-data="new { myVal = true }"

But I am getting the value as undefined.

Please suggest the steps how I can access the server side global data like appsettings in angular 2 component.

@MarkPieszak
Copy link
Contributor

Do a view source, it's an object on the window that you need to access.

@abhilash1990
Copy link
Author

I am trying to access it like this (window as any).myVal

Which object of window can you please explain.

@SteveSandersonMS
Copy link
Member

Just like @MarkPieszak suggested, I'd recommend having a look at the generated HTML file and seeing what property or properties get assigned to the window object. Somewhere in the HTML will be some code similar to window.someProperty = { ... your data ... }.

@irejwanul
Copy link

irejwanul commented Jan 12, 2018

Hi, if you set globals: { postList: [ '<h1>Welcome, ${params.data.userName}</h1>' ] }
in your boot.server.ts
Then you can retrieve in any component with following code:
(<any>window)._this.postList;

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants