Example of using asp-prerender-data to get server-supplied data to both server and client JS
This commit is contained in:
Родитель
ad645cbfe9
Коммит
678e230021
|
@ -14,7 +14,8 @@ import { sharedConfig } from './app.module.shared';
|
|||
...sharedConfig.imports
|
||||
],
|
||||
providers: [
|
||||
{ provide: 'ORIGIN_URL', useValue: location.origin }
|
||||
{ provide: 'ORIGIN_URL', useValue: location.origin },
|
||||
{ provide: 'PRERENDERING_DATA', useValue: (window as any).PRERENDERING_DATA }
|
||||
]
|
||||
})
|
||||
export class AppModule {
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
<h1>Weather forecast</h1>
|
||||
|
||||
<p>Prerendering data: {{ prerenderingDataString }}</p>
|
||||
|
||||
<p>This component demonstrates fetching data from the server.</p>
|
||||
|
||||
<p *ngIf="!forecasts"><em>Loading...</em></p>
|
||||
|
|
|
@ -7,8 +7,11 @@ import { Http } from '@angular/http';
|
|||
})
|
||||
export class FetchDataComponent {
|
||||
public forecasts: WeatherForecast[];
|
||||
public prerenderingDataString: string;
|
||||
|
||||
constructor(http: Http, @Inject('ORIGIN_URL') originUrl: string, @Inject('PRERENDERING_DATA') prerenderingData: any) {
|
||||
this.prerenderingDataString = JSON.stringify(prerenderingData);
|
||||
|
||||
constructor(http: Http, @Inject('ORIGIN_URL') originUrl: string) {
|
||||
http.get(originUrl + '/api/SampleData/WeatherForecasts').subscribe(result => {
|
||||
this.forecasts = result.json() as WeatherForecast[];
|
||||
});
|
||||
|
|
|
@ -11,7 +11,8 @@ enableProdMode();
|
|||
export default createServerRenderer(params => {
|
||||
const providers = [
|
||||
{ provide: INITIAL_CONFIG, useValue: { document: '<app></app>', url: params.url } },
|
||||
{ provide: 'ORIGIN_URL', useValue: params.origin }
|
||||
{ provide: 'ORIGIN_URL', useValue: params.origin },
|
||||
{ provide: 'PRERENDERING_DATA', useValue: params.data }
|
||||
];
|
||||
|
||||
return platformDynamicServer(providers).bootstrapModule(AppModule).then(moduleRef => {
|
||||
|
@ -26,7 +27,8 @@ export default createServerRenderer(params => {
|
|||
// completing the request in case there's an error to report
|
||||
setImmediate(() => {
|
||||
resolve({
|
||||
html: state.renderToString()
|
||||
html: state.renderToString(),
|
||||
globals: { PRERENDERING_DATA: params.data }
|
||||
});
|
||||
moduleRef.destroy();
|
||||
});
|
||||
|
|
|
@ -2,7 +2,11 @@
|
|||
ViewData["Title"] = "Home Page";
|
||||
}
|
||||
|
||||
<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
|
||||
<app asp-prerender-module="ClientApp/dist/main-server"
|
||||
asp-prerender-data="new {
|
||||
IsGoldUser = true,
|
||||
Cookies = ViewContext.HttpContext.Request.Cookies
|
||||
}">Loading...</app>
|
||||
|
||||
<script src="~/dist/vendor.js" asp-append-version="true"></script>
|
||||
@section scripts {
|
||||
|
|
Загрузка…
Ссылка в новой задаче