我在树莓派中有一个网络应用程序和一个 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/