获取angular2 component.ts上的本地IP

sca*_*bie 4 ip web angular

我在覆盆子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'];
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在覆盆子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'];
        })
    }
Run Code Online (Sandbox Code Playgroud)

我已经测试过,如果我手动将IP放在代码中,虽然它只是用于测试,但我不想手动输入.

Geo*_*ley 11

你可以得到origin通过window.location.origin.有关详细信息,请点击此处

 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'];
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,如果你只想要`ip`或`hostname`我的意思是没有`port`你可以使用`window.location.hostname` (2认同)