Get local IP on angular2 component.ts

2019-05-04 17:47发布

问题:

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

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'];
        })
    }
}

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.

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'];
        })
    }

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.

回答1:

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'];
    })
}


标签: angular web ip