Project

General

Profile

1
import 'angular2-universal/polyfills';
2

    
3
import * as path from 'path';
4
import * as express from 'express';
5
import * as bodyParser from 'body-parser';
6

    
7
// Angular 2 Universal
8
import {
9
  provide,
10
  enableProdMode,
11
  expressEngine,
12
  REQUEST_URL,
13
  ORIGIN_URL,
14
  BASE_URL,
15
  NODE_ROUTER_PROVIDERS,
16
  NODE_HTTP_PROVIDERS,
17
  ExpressEngineConfig
18
} from 'angular2-universal';
19

    
20
// Application
21
import {App} from './app/app.component';
22

    
23
const app = express();
24
const ROOT = path.join(path.resolve(__dirname, '..'));
25

    
26
enableProdMode();
27

    
28
// Express View
29
app.engine('.html', expressEngine);
30
app.set('views', __dirname);
31
app.set('view engine', 'html');
32

    
33
app.use(bodyParser.json());
34

    
35

    
36
function ngApp(req, res) {
37
  let baseUrl = '/';
38
  let url = req.originalUrl || '/';
39

    
40
  let config: ExpressEngineConfig = {
41
    directives: [ App ],
42
    platformProviders: [
43
      provide(ORIGIN_URL, {useValue: 'http://localhost:3000'}),
44
      provide(BASE_URL, {useValue: baseUrl}),
45
    ],
46
    providers: [
47
      provide(REQUEST_URL, {useValue: url}),
48
      NODE_ROUTER_PROVIDERS,
49
      NODE_HTTP_PROVIDERS,
50
    ],
51
    async: true,
52
    preboot: false // { appRoot: 'app' } // your top level app component selector
53
  };
54

    
55
  res.render('index', config);
56
}
57

    
58
function indexFile(req, res) {
59
  res.sendFile('/index.html', {root: __dirname});
60
}
61

    
62
// Serve static files
63
app.use(express.static(ROOT, {index: false}));
64

    
65
// Our API for demos only
66
app.get('/data.json', (req, res) => {
67
  res.json({
68
    data: 'This fake data came from the server.'
69
  });
70
});
71

    
72
// Routes with html5pushstate
73
app.use('/', ngApp);
74
app.use('/home', ngApp);
75
app.use('/search', ngApp);
76
// Server
77
app.listen(3000, () => {
78
  console.log('Listening on: http://localhost:3000');
79
});
(4-4/5)