你可以通過實體傳遞從Express服務器到應用的角度,像這樣...... 在你server.ts文件(這是貫徹落實express.js服務器),你需要添加一個新的提供者(見'extraProviders')
...
app.engine('html', (_, options, callback) => {
const opts = {
document: template
,url: options.req.url
,extraProviders: [
//pass the express.js request object through to the angular4 app
{ provide: 'request', useFactory:() => options.req }
]
};
renderModuleFactory(AppServerModuleNgFactory, opts)
.then(html => callback(null, html));
});
...
然後在你的角4的應用程序,你可以注入請求對象到您的服務或組件,像這樣:
import { Injectable, Injector, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
@Injectable()
export class SomeService {
constructor(
private injector: Injector
,@Inject(PLATFORM_ID) private platformId: Object
){
if (isPlatformServer(this.platformId)) {
// -> server rendered
let requestObj = this.injector.get('request');
let ip = requestObj.connection.remoteAddress;
} else {
// -> browser rendered
}
}
...
這是我的完整server.ts file:
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
import * as compression from 'compression';
const PORT = 4200;
enableProdMode();
const app = express();
let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();
app.engine('html', (_, options, callback) => {
const opts = {
document: template
,url: options.req.url
,extraProviders: [
{ provide: 'request', useFactory:() => options.req }
,{ provide: 'host', useFactory:() => options.req.get('host') }
]
};
renderModuleFactory(AppServerModuleNgFactory, opts)
.then(html => callback(null, html));
});
app.set('view engine', 'html');
app.set('views', 'src');
app.use(compression());
app.get('*.*', express.static(join(__dirname, '..', 'dist')));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(PORT,() => {
console.log(`listening on http://localhost:${PORT}!`);
});