Make async data fetching work on the server with Angular 2

This commit is contained in:
SteveSandersonMS
2016-04-05 20:31:21 +01:00
parent 89c8dd3b36
commit c8a7ac95a9
2 changed files with 19 additions and 8 deletions

View File

@@ -6,15 +6,22 @@ import { App } from './components/app/app';
export default function (params: any): Promise<{ html: string, globals?: any }> { export default function (params: any): Promise<{ html: string, globals?: any }> {
const serverBindings = [ 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.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 />', App, serverBindings).then(html => { return ngUniversal.bootloader({
directives: [App],
providers: serverBindings,
async: true,
preboot: false,
// TODO: Render just the <app> component instead of wrapping it inside an extra HTML document
// Waiting on https://github.com/angular/universal/issues/347
template: '<!DOCTYPE html>\n<html><head></head><body><app></app></body></html>'
}).serializeApplication().then(html => {
return { html }; return { html };
}); });
} }

View File

@@ -9,7 +9,11 @@ export class FetchData {
public forecasts: WeatherForecast[]; public forecasts: WeatherForecast[];
constructor(http: Http) { 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: <any>{ Connection: 'keep-alive' } // Workaround for RC1 bug. TODO: Remove this after updating to RC2
}).subscribe(result => {
this.forecasts = result.json(); this.forecasts = result.json();
}); });
} }