angular - 在 angular2 component.ts 上获取本地 IP

标签 angular web ip

我在树莓派中有一个网络应用程序和一个 API。 Web 应用程序使用 HTTP GET 请求 API 来显示其内容

现在,在网络应用 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 获取数据。

我假设这是因为“本地主机”,一旦无法使用静态 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获取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'];
    })
}

关于angular - 在 angular2 component.ts 上获取本地 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208629/

相关文章:

web - 如何在golang web中gzip一个模板

java - 为什么我从数据包中得到负目标地址

javascript - 返回由链式 JavaScript Promise 创建的对象

angular - routerLink 附加我的链接

tomcat - 使用 visualvm 分析 Tomcat Web 应用程序

c++ - 从 C++ 缓冲区中提取 IP 地址(Linux 套接字)

ip - kubernetes 的外部 ip 在 minikube 中显示 <nodes>

Angular HttpClient 行为原始 HTML

angular - 无法让 Angular4 使用延迟加载和动画(使用 BrowserAnimationsModule)

c - 如何修改这个顺序网络程序以获得更好的性能?