在Angular Universal中获取远程地址

时间:2017-06-05 13:20:05

标签: angular angular-universal

我希望在服务器端呈现请求时获得角度4通用的远程IP地址。我尝试使用带有以下内容的zone.js在角度服务中获取节点请求对象,但不是为了获取它,

var req = Zone.current.get('req') || {};
var headers = (req && req.headers) ? req.headers : {};
console.log("Zone Headers: " + JSON.stringify(headers));

有没有获取IP地址?我想将IP地址传递给API以获取基于位置的结果。

怎么做?请帮忙。

1 个答案:

答案 0 :(得分:2)

您可以将对象从快速服务器传递到角度应用程序,如此... 在 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));
});
...

然后在您的Angular 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 文件:

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}!`);
});