In this short blog post, I will show you how to get the ip address of the user.
_I'm using v5 for this tutorial. If you are using v2/v4, just replace the HttpClient with just Http._
Here it goes:
import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
ipAddress:any;
constructor(private http: HttpClient){
this.http.get('https://jsonip.com')
.subscribe( data => {
this.ipAddress = data.ip;
})
}
}This should work now. Though the code editor is telling me that this line
this.ipAddress = data.ip;
is wrong.
Looking at the official docs for the http client, I need to tell the httpclient what the type response will be so I will create an interface with just a ip property of string.
interface ItemsResponse {
ip: string;
}And add it like this
this.http.get<ItemsResponse>('https://jsonip.com')That’s it.
Thanks for reading.
Here’s the stackblitz demo