How To Get The Client IP Address in Angular Application?
It’s very simple to have our client address in angular application with so many open sources API address those return directly client’s IP address as client request from its own browser to API.
In this article, I’ll use http://api.ipify.org/?format=json this API for Client IP Address in JSON.
So, the very first thing that you have to create an Angular Application using Angular CLI and now follow the following steps.
Step 1:
Add a new angular service in your app using CLI with the following command:
ng g service IpService
Now after this command you must have two new files in your angular app source.
Go to Folder explorer and check for new files.
Step 2:
Now open app.module.ts file and import HttpClientModule from “@angular/common/http” so that you can work with http:// services and can call API.
import { HttpClientModule } from "@angular/common/http";
imports: [
...,HttpClientModule
]
Now Open your Service File and use the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class IpServiceService {
constructor(private http:HttpClient) { }
public getIPAddress()
{
return this.http.get("http://api.ipify.org/?format=json");
}
}
Here in this code first we imported HttpClient from @angular/common/http and injected a dependency in service constructor and at last, created a function named as getIPAddress() from where we’ll return an Observable from http://api.ipify.org/?format=json.
Step 3:
Now open your component file as I did in my app.component.ts, firstly import and inject service object in component’s constructor and Subscribe getIpAddress() function from your service into a local variable, as following code:
import { Component, OnInit } from '@angular/core';
import { IpServiceService } from './ip-service.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private ip:IpServiceService){}
title = 'DemoApp';
ipAddress:string;
ngOnInit()
{
this.getIP();
}
getIP()
{
this.ip.getIPAddress().subscribe((res:any)=>{
this.ipAddress=res.ip;
});
}
}
Now, at last, open your app.component.html and try to print that variable using interpolation brackets.
<div class="container">
<p>Your IP Adderss : {{ipAddress}}</p>
</div>
Step 4:
Serve your angular app and open in your browser to check the IP Address, so open terminal in visual studio code and write command:
Ng serve –open
You might get the output as follows:
Here is the client IP Address, Hope you enjoyed it.