Introduction
It’s very simple to have our client address in an Angular application. With so many open sources, API addresses directly return the client’s IP address as a client request from its own browser to the API.
In this article, I’ll use
this API for the Client IP Address in JSON.
First, you have to create an Angular Application using Angular CLI.
Step 1
Add a new angular service in your app using CLI with the following command:
"ng g service IpService"
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
- ]
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. At last, we created a function named getIPAddress() from where we’ll return an Observable from
here.
Step 3
Now open your component file as I did in my app.component.ts. Firstly, import and inject the service object in the component’s constructor and subscribe the getIpAddress() function from your service into a local variable, as in the 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;
- });
- }
- }
Finally, open your app.component.html and try to print that variable using interpolation brackets.
- <div class="container"> <p>Your IP Address : {{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 the command:
Ng serve –open
You might get the output as shown below:
Here is the client IP Address, hope you enjoyed it!