获取angular2 component.ts上的本地IP [英] Get local IP on angular2 component.ts

查看:467
本文介绍了获取angular2 component.ts上的本地IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在覆盆子PI中有一个网络应用和API。 Web应用程序使用HTTP GET请求到API以显示其内容

I have a web app and an API inside a raspberry PI. The web app uses HTTP GET requisitions to the API to display its content

现在,在Web应用程序组件内部.ts:

Now, inside the web app component.ts:

export class AppComponent implements OnInit {

    results = {};

    constructor(private http: HttpClient) {}
    ngOnInit(): void {

        var url = 'http://localhost:8000/api/';
        var endpoint = 'test/';

        this.http.get(url + endpoint).subscribe(data => {
          this.results = data['test'];
        })
    }
}

当我在浏览器上打开网络应用程序时,这可行。
但是,当使用覆盆子的IP和应用程序正在运行的端口从其他设备打开Web应用程序时,我无法从API获取数据。

This works when I open the web app on a browser INSIDE the raspberry. However, when opening the web app from another device using the raspberry's IP and the port the app is running, I can't get the data from the API.

我认为这是因为'localhost',一旦这个锉刀不能用静态IP设置我想要检索它的本地IP,做类似的东西:

I assume it's because of the 'localhost', and once this rasp CANNOT BE SET WITH A STATIC IP I'd like to retrieve its local IP, to make something like:

    ngOnInit(): void {

        var ip = <some code <-- HELP>
        var url = 'http://' + ip + ':8000/api/';
        var endpoint = 'test/';

        this.http.get(url + endpoint).subscribe(data => {
          this.results = data['test'];
        })
    }

我已经测试过,如果我手动将IP放在代码中,它可以运行它只是用于测试,我不想手动输入。

And I've tested, if I put the IP manually in the code it works, though it was just for test, I don't want to input it manually.

推荐答案

你可以得到 origin by window.location.origin 。有关详细信息,请查看此处

You can get the origin by window.location.origin. For more details check here

 ngOnInit(): void {

    var ip = window.location.origin // this will give you the ip:port
    //if you just want the ip or hostname you can use window.location.hostname
    var url =  ip + '/api/';
    var endpoint = 'test/';

    this.http.get(url + endpoint).subscribe(data => {
      this.results = data['test'];
    })
}

这篇关于获取angular2 component.ts上的本地IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆