ng2 2.0, Universal 2.0, TS 2.0, Preboot 4.*

This commit is contained in:
Mark Pieszak
2016-09-19 09:12:03 +01:00
committed by SteveSandersonMS
parent b71d139eb5
commit ce0d2089d2
18 changed files with 273 additions and 1166 deletions

View File

@@ -1,36 +1,76 @@
import 'angular2-universal/polyfills';
import * as ngCore from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { provideRouter } from '@angular/router';
import * as ngUniversal from 'angular2-universal';
import { BASE_URL, ORIGIN_URL, REQUEST_URL } from 'angular2-universal/common';
import { App } from './components/app/app';
// the polyfills must be the first thing imported in node.js
import 'angular2-universal-polyfills';
// Angular 2
import { enableProdMode } from '@angular/core';
// Angular2 Universal
import { platformNodeDynamic } from 'angular2-universal';
// Application imports
import { MainModule } from './main.node';
import { App } from './components';
import { routes } from './routes';
const bootloader = ngUniversal.bootloader({
async: true,
preboot: false,
platformProviders: [
ngCore.provide(APP_BASE_HREF, { useValue: '/' }),
]
});
// enable prod for faster renders
enableProdMode();
export default function (params: any): Promise<{ html: string, globals?: any }> {
const config: ngUniversal.AppConfig = {
directives: [App],
providers: [
ngCore.provide(ORIGIN_URL, { useValue: params.origin }),
ngCore.provide(REQUEST_URL, { useValue: params.url }),
...ngUniversal.NODE_HTTP_PROVIDERS,
provideRouter(routes),
...ngUniversal.NODE_LOCATION_PROVIDERS,
],
// 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>'
declare var Zone: any;
export default function (params: any) : Promise<{ html: string, globals?: any }> {
const doc = `
<!DOCTYPE html>\n
<html>
<head></head>
<body>
<app></app>
</body>
</html>
`;
// hold platform reference
var platformRef = platformNodeDynamic();
var platformConfig = {
ngModule: MainModule,
document: doc,
preboot: false,
baseUrl: '/',
requestUrl: params.url,
originUrl: params.origin
};
return bootloader.serializeApplication(config).then(html => {
return { html };
// defaults
var cancel = false;
const _config = Object.assign({
get cancel() { return cancel; },
cancelHandler() { return Zone.current.get('cancel') }
}, platformConfig);
// for each user
const zone = Zone.current.fork({
name: 'UNIVERSAL request',
properties: _config
});
return Promise.resolve(
zone.run(() => {
return platformRef.serializeModule(Zone.current.get('ngModule'))
})
).then(html => {
if (typeof html !== 'string' ) {
return { html : doc };
}
return { html };
}).catch(err => {
console.log(err);
return { html : doc };
});
}