UNPKG

2.46 kBMarkdownView Raw
1# Angular Express Engine
2
3This is an Express Engine for running Angular Apps on the server for server side rendering.
4
5## Usage
6
7`npm install @nguniversal/express-engine --save`
8
9To use it, set the engine and then route requests to it
10
11```ts
12import express from 'express';
13import { ngExpressEngine } from '@nguniversal/express-engine';
14
15const app = express();
16
17// Set the engine
18app.engine(
19 'html',
20 ngExpressEngine({
21 bootstrap: ServerAppModule, // Give it a module to bootstrap
22 }),
23);
24
25app.set('view engine', 'html');
26
27app.get('/**/*', (req: Request, res: Response) => {
28 res.render('../dist/index', {
29 req,
30 res,
31 });
32});
33```
34
35## Configuring the URL and Document
36
37It is possible to override the default URL and document fetched when the rendering engine
38is called. To do so, simply pass in a `url` and/or `document` string to the renderer as follows:
39
40```ts
41app.get('/**/*', (req: Request, res: Response) => {
42 let url = 'http://someurl.com';
43 let doc = '<html><head><title>New doc</title></head></html>';
44 res.render('../dist/index', {
45 req,
46 res,
47 url,
48 document: doc,
49 });
50});
51```
52
53## Extra Providers
54
55Extra Providers can be provided either on engine setup
56
57```ts
58app.engine(
59 'html',
60 ngExpressEngine({
61 bootstrap: ServerAppModule,
62 providers: [ServerService],
63 }),
64);
65```
66
67## Advanced Usage
68
69### Request based Bootstrap
70
71The Bootstrap module as well as more providers can be passed on request
72
73```ts
74app.get('/**/*', (req: Request, res: Response) => {
75 res.render('../dist/index', {
76 req,
77 res,
78 bootstrap: OtherServerAppModule,
79 providers: [OtherServerService],
80 });
81});
82```
83
84### Using the Request and Response
85
86The Request and Response objects are injected into the app via injection tokens.
87You can access them by @Inject
88
89```ts
90import { Request } from 'express';
91import { REQUEST } from '@nguniversal/express-engine/tokens';
92
93@Injectable()
94export class RequestService {
95 constructor(@Inject(REQUEST) private request: Request) {}
96}
97```
98
99If your app runs on the client side too, you will have to provide your own versions of these in the client app.
100
101### Using a Custom Callback
102
103You can also use a custom callback to better handle your errors
104
105```ts
106app.get('/**/*', (req: Request, res: Response) => {
107 res.render(
108 '../dist/index',
109 {
110 req,
111 res,
112 },
113 (err: Error, html: string) => {
114 res.status(html ? 200 : 500).send(html || err.message);
115 },
116 );
117});
118```