Angular通用SSR,首先找到用户IP的调用是从服务器而不是客户端?

时间:2019-09-18 05:57:44

标签: angular angular-universal server-side-rendering

我们制作了Angular通用服务器端渲染应用程序,以便在HTML代码中显示SEO目的的视图源。我们已经在我们的应用程序中实现了本地化,以根据国家/地区提供数据。我们在应用程序开始时找到该IP,然后使用该IP获取该特定国家/地区的数据。

问题在于,在SSR之后,应用程序首先从服务器进行渲染,而ip调用从服务器进行并找到服务器的ip。但是我们需要客户端浏览器的IP。他们有什么办法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要为angular应用提供客户端IP地址

app.engine('html', (_, options, callback) =>
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'clientIPAddress',
        useValue: options.req.connection.remoteAddress, //Provides the client IP address to angular
      },
    ],
  })(_, options, callback)
)

然后在您的角度应用程序中,注入该值

import { Injectable, Inject, Optional } from '@angular/core';


export class YourServiceOrComponent{
constructor(@Optional() @Inject('clientIPAddress') ipAddress: string) 
{
    if(ipAddress)
    {
        //Server side
    }
    else
    {
    //client side
    }
}