Skip to content

Commit c8a7ac9

Browse files
Make async data fetching work on the server with Angular 2
1 parent 89c8dd3 commit c8a7ac9

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

templates/Angular2Spa/ClientApp/boot-server.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,22 @@ import { App } from './components/app/app';
66

77
export default function (params: any): Promise<{ html: string, globals?: any }> {
88
const serverBindings = [
9-
ngRouter.ROUTER_BINDINGS,
10-
ngUniversal.HTTP_PROVIDERS,
11-
ngUniversal.NODE_LOCATION_PROVIDERS,
12-
ngCore.provide(ngRouter.APP_BASE_HREF, { useValue: '/' }),
139
ngCore.provide(ngUniversal.BASE_URL, { useValue: params.absoluteUrl }),
14-
ngCore.provide(ngUniversal.REQUEST_URL, { useValue: params.url })
10+
ngCore.provide(ngUniversal.REQUEST_URL, { useValue: params.url }),
11+
ngCore.provide(ngRouter.APP_BASE_HREF, { useValue: '/' }),
12+
ngUniversal.NODE_HTTP_PROVIDERS,
13+
ngUniversal.NODE_ROUTER_PROVIDERS
1514
];
16-
17-
return ngUniversal.renderDocument('<app />', App, serverBindings).then(html => {
15+
16+
return ngUniversal.bootloader({
17+
directives: [App],
18+
providers: serverBindings,
19+
async: true,
20+
preboot: false,
21+
// TODO: Render just the <app> component instead of wrapping it inside an extra HTML document
22+
// Waiting on https://github.com/angular/universal/issues/347
23+
template: '<!DOCTYPE html>\n<html><head></head><body><app></app></body></html>'
24+
}).serializeApplication().then(html => {
1825
return { html };
1926
});
2027
}

templates/Angular2Spa/ClientApp/components/fetch-data/fetch-data.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ export class FetchData {
99
public forecasts: WeatherForecast[];
1010

1111
constructor(http: Http) {
12-
http.get('/api/SampleData/WeatherForecasts').subscribe(result => {
12+
// TODO: Switch to relative URL once angular-universal supports them
13+
// https://github.com/angular/universal/issues/348
14+
http.get('http://localhost:5000/api/SampleData/WeatherForecasts', {
15+
headers: <any>{ Connection: 'keep-alive' } // Workaround for RC1 bug. TODO: Remove this after updating to RC2
16+
}).subscribe(result => {
1317
this.forecasts = result.json();
1418
});
1519
}

0 commit comments

Comments
 (0)