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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - https://code-sample.com and https://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions