加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

获取angular2 component.ts上的本地IP

发布时间:2020-12-17 17:57:20 所属栏目:安全 来源:网络整理
导读:我在覆盆子PI中有一个Web应用程序和一个API. Web应用程序使用HTTP GET请求来显示其内容 现在,在web应用程序component.ts中: export class AppComponent implements OnInit { results = {}; constructor(private http: HttpClient) {} ngOnInit(): void { va
我在覆盆子PI中有一个Web应用程序和一个API. Web应用程序使用HTTP GET请求来显示其内容

现在,在web应用程序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'];
        })
    }
}

当我在覆盆子INSIDE上打开Web应用程序时,这种方法有效.
但是,当使用raspberry的IP和应用程序正在运行的端口从其他设备打开Web应用程序时,我无法从API获取数据.

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

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放在代码中,虽然它只是用于测试,但我不想手动输入.

解决方法

您可以通过window.location.origin获取原点.有关详细信息,请查看 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'];
    })
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读