如何从 angular 中的浏览器获取客户端 ip 地址(打字稿)

How to get the client ip address from browser in angular (typescript)

嘿,如果你能给我提供一个示例,其中类型脚本 class 可以获取客户端 IP 地址和客户端正在使用的浏览器,并在变量中设置这些值,我将不胜感激

我想在类型脚本中而不是在 java 脚本中执行此操作是否可行,如果不行,如何使用类型脚本执行此操作

- 所以例如我可以 1)在将表单提交到后端数据库时设置这些变量 2)例如,我可以为用户显示他正在使用的浏览器 任何帮助将不胜感激谢谢

你应该这样试试

var json = 'http://ipv4.myexternalip.com/json';
   $http.get(json).then(function(result) {
    console.log(result.data.ip)
},  function(e) {
   alert("error");
});

试试这个:

创建提供程序并添加具有所需依赖项的函数:

import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/Rx';


 //  Function :

getIP(): Observable<Data[]> {
    return this.http.get('http://ipinfo.io') // ...using post request
    .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
    .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}

控制器代码:

getIP() {
    this.loading = true;
    this._myIPService.getIP()
    .subscribe(
        IPDetails => this.IppDetails,
        error =>  this.errorMessage = <any>error
        );
}

您将在 this.IppDetails

中获得 IP 的所有详细信息

非常感谢,很好的解决方案 我把它作为我的问题的基础,但我没有解决它,因为它给了我互联网服务器的 public IP。 对于使用 DHCP 的内部网络,通过以下方式更改 URL:

  getIpCliente(): Observable<string> {
      return this.http.get('http://api.ipify.org/?format=jsonp&callback=JSONP_CALLBACK') // ...using post request '
      .map((res:Response) => {console.log('res ', res);
                              console.log('res.json() ', res.text());
                              //console.log('parseado ', JSON.parse(res.text()));
                              console.log('parseado  stringify ', JSON.stringify(res.text()));
                              let ipVar = res.text();
                              let num = ipVar.indexOf(":");
                              let num2 = ipVar.indexOf("\"});");
                              ipVar = ipVar.slice(num+2,num2);
                              console.log('ipVar -- ',ipVar);
                              return ipVar}); // ...and calling .json() on the response to return data
      //.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
  }

希望能为各位朋友服务

尝试https://geolocation-db.com的服务获取用户的public ip地址。

import { HttpClient } from "@angular/common/http";
import { catchError, tap } from "rxjs/operators";

this.http.get<any>('https://geolocation-db.com/json/')
  .pipe(
    catchError(err => {
      return throwError(err);
    }),
    tap(response => {
      console.log(response.IPv4);
    })
  )