Get Client IP Address Angular

How To Get Client IP Address and Client Browser In Angular?

Get Client IP Address Angular 4 and 5 -


To Get Client IP Address in Angular 4 and 5, the following Steps as given below –
1.      Create Service
2.      Used the Service in your components
3.      Result

Create Service for Get IP Address
- my-user-serv.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

@Injectable()
export class MyUserServService {

  constructor(private http: HttpClient) { }

 //Get IP Adress using http://freegeoip.net/json/?callback
  getIpAddress() {
      return this.http
            .get('http://freegeoip.net/json/?callback')
            .map(response => response || {})
            .catch(this.handleError);
  }

  private handleError(error: HttpErrorResponse):
      Observable<any> {
        //Log error in the browser console
        console.error('observable error: ', error);

        return Observable.throw(error);
    }
}



Used the Service in your user components
-user.component.ts
import { Component, OnInit } from '@angular/core';
import {MyUserServService} from '../my-user-serv.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(private userService: MyUserServService) { }

  //Init the user Servies for Get The client IP Adress.
  ngOnInit(): void {
    console.log("ip");
    this.userService.getIpAddress().subscribe(data => {
      console.log(data);
    });
  }
}

The Result Looks like –
{
"ip":"122.177.88.235",
"country_code":"IN",
"country_name":"India",
"region_code":"UP",
"region_name":"Uttar Pradesh",
"city":"Ghaziabad",
"zip_code":"201001",
"time_zone":"Asia/Kolkata",
"latitude":28.6667,
"longitude":77.4333,
"metro_code":0
}


Stayed InformedAngular 4 and Angular 5 Docs
I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^