Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get local IP on angular2 component.ts

Tags:

angular

web

ip

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.

like image 516
Laura Martins Avatar asked Nov 09 '17 17:11

Laura Martins


1 Answers

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'];
    })
}
like image 166
Muhammad Usman Avatar answered Nov 10 '22 04:11

Muhammad Usman