python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

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