如何使用angularjs

时间:2017-05-01 06:40:06

标签: angularjs

需要从angularjs代码中获取系统IP地址。

我在谷歌搜索过。每个人都建议来自js的第三方。

所以我不想打电话来获取IP?

有没有办法从angularjs获取IP?

我的实际情况是。

需要在每次休息呼叫中发送系统IP

3 个答案:

答案 0 :(得分:9)

如何使用AngularJS获取系统IP地址

使用freegeoip.net

上的位置服务

angular.module("myApp",[]).run(function($rootScope, $http) {
  var url = "//freegeoip.net/json/";
  $http.get(url).then(function(response) {
    console.log(response.data.ip);
    $rootScope.ip = response.data.ip;
  });
});
<script src="https://unpkg.com/angular/angular.js"></script>
<div ng-app="myApp">
  IP address = {{ip}}
</div>

更新

此API端点已弃用,将于2018年7月1日停止工作。有关详细信息,请访问:https://github.com/apilayer/freegeoip#readme

答案 1 :(得分:0)

It will work in angular 2/4/6/...

 import { HttpClient } from '@angular/common/http';

    export class AppComponent implements OnInit {
            ipAddress: any;
            constructor(private http: HttpClient ) {
            this.http.get('https://jsonip.com').subscribe((ipOfNetwork) => 
           this.ipAddress =  ipOfNetwork['ip']);
        }

        ngOnInit() {
        console.log(this.ipAddress);
        }
        }

答案 2 :(得分:-1)

Get client IP in javascript/angularjs 这个问题很容易满足您的需求 这种方法也很容易使用。 ng-ip-address article might be helpful

在您的构建中包含ngIpAddress.min.js或ngIpAddress.vanilla.min.js或直接在标记中包含模块定义中的模块:

angular  
.module('App', [  
    'ng-ip-address',
    ... // other dependencies   
]);

要包含在您的视图中,请包含此

<input type="text" ng-model="model" ng-ip-address />