How to get client IP Address in Angular Apps?

In this article, we discuss how to get IP address of the client in our application. First, we need to “Create Service” to get the IP Address.
visitors.service


import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class VisitorsService {

  constructor(
    private http: HttpClient
  ) { 

  }
 
  getIpAddress() {
    return this.http
          .get('https://api.ipify.org/?format=json')
          .pipe(
            catchError(this.handleError)
          );
  } 

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }

}



We need to import our services in the app module for use.
app.module.ts



import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

import { VisitorsService } from './services/visitors.service';

@NgModule({
  imports:      [ BrowserModule, FormsModule,HttpClientModule ],
  declarations: [ AppComponent, HelloComponent ],
  providers:    [VisitorsService],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Lets use these service in our component.


<h3> My public IP address is </h3> 
<p>{{ipaddress}}</p>


import { Component,OnInit } from '@angular/core';

import { VisitorsService } from './services/visitors.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit   {
  name = 'Angular';

   ipaddress:string = '';
   constructor(
      private visitorsService:VisitorsService
   ){

   }

   ngOnInit(){

      this.visitorsService.getIpAddress().subscribe(res => {

        this.ipaddress = res['ip'];
        //console.log(res);

      });
   }
}




Below is the running embedded code for Getting Client IP Address.

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 2
  •  
  •