From c8a7ac95a902eb4d05935f279850b3826d62feb6 Mon Sep 17 00:00:00 2001 From: SteveSandersonMS Date: Tue, 5 Apr 2016 20:31:21 +0100 Subject: [PATCH] Make async data fetching work on the server with Angular 2 --- .../Angular2Spa/ClientApp/boot-server.ts | 21 ++++++++++++------- .../components/fetch-data/fetch-data.ts | 6 +++++- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/templates/Angular2Spa/ClientApp/boot-server.ts b/templates/Angular2Spa/ClientApp/boot-server.ts index 5847f94..71ea842 100644 --- a/templates/Angular2Spa/ClientApp/boot-server.ts +++ b/templates/Angular2Spa/ClientApp/boot-server.ts @@ -6,15 +6,22 @@ import { App } from './components/app/app'; export default function (params: any): Promise<{ html: string, globals?: any }> { const serverBindings = [ - ngRouter.ROUTER_BINDINGS, - ngUniversal.HTTP_PROVIDERS, - ngUniversal.NODE_LOCATION_PROVIDERS, - ngCore.provide(ngRouter.APP_BASE_HREF, { useValue: '/' }), ngCore.provide(ngUniversal.BASE_URL, { useValue: params.absoluteUrl }), - ngCore.provide(ngUniversal.REQUEST_URL, { useValue: params.url }) + ngCore.provide(ngUniversal.REQUEST_URL, { useValue: params.url }), + ngCore.provide(ngRouter.APP_BASE_HREF, { useValue: '/' }), + ngUniversal.NODE_HTTP_PROVIDERS, + ngUniversal.NODE_ROUTER_PROVIDERS ]; - - return ngUniversal.renderDocument('', App, serverBindings).then(html => { + + return ngUniversal.bootloader({ + directives: [App], + providers: serverBindings, + async: true, + preboot: false, + // TODO: Render just the component instead of wrapping it inside an extra HTML document + // Waiting on https://github.com/angular/universal/issues/347 + template: '\n' + }).serializeApplication().then(html => { return { html }; }); } diff --git a/templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts b/templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts index 96f8fc4..ba245e9 100644 --- a/templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts +++ b/templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts @@ -9,7 +9,11 @@ export class FetchData { public forecasts: WeatherForecast[]; constructor(http: Http) { - http.get('/api/SampleData/WeatherForecasts').subscribe(result => { + // TODO: Switch to relative URL once angular-universal supports them + // https://github.com/angular/universal/issues/348 + http.get('http://localhost:5000/api/SampleData/WeatherForecasts', { + headers: { Connection: 'keep-alive' } // Workaround for RC1 bug. TODO: Remove this after updating to RC2 + }).subscribe(result => { this.forecasts = result.json(); }); }