Reputation: 327
Hey there I would really appreciate it if you can provide me with an example where a type script class can get the client's IP address and the browser that the client is using and set those values in variables
I want to do this in type script, not in javascript is that possible and if not how to do it with type script
- So For Example I can
set those variables while submitting the form to the database in the back end
I can for example display for the user the browser he is using any help would be appreciated thanks
Upvotes: 19
Views: 98770
Reputation: 179
I took it as a basis for my problem but I did not solve it because it gave me the public IP of the internet server. For an internal network with DHCP, change the URL by the following:
getIpCliente(): Observable<string> {
return this.http
.get('http://api.ipify.org/?format=jsonp&callback=JSONP_CALLBACK')
.map((res: Response) => {
console.log('res ', res);
console.log('res.json() ', res.text());
console.log('parseado stringify ', JSON.stringify(res.text()));
let ipVar = res.text();
let num = ipVar.indexOf(":");
let num2 = ipVar.indexOf("\"});");
ipVar = ipVar.slice(num+2,num2);
return ipVar
}
);
}
Upvotes: 14
Reputation: 12934
Try the services of https://geolocation-db.com to get the public ip address of the user.
import { HttpClient } from "@angular/common/http";
import { catchError, tap } from "rxjs/operators";
this.http.get<any>('https://geolocation-db.com/json/')
.pipe(
catchError(err => {
return throwError(err);
}),
tap(response => {
console.log(response.IPv4);
})
)
Upvotes: 5
Reputation: 8156
Try This :
Create Provider and add function with required dependencies :
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/Rx';
// Function :
getIP(): Observable<Data[]> {
return this.http.get('http://ipinfo.io') // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}
Controller Code :
getIP() {
this.loading = true;
this._myIPService.getIP()
.subscribe(
IPDetails => this.IppDetails,
error => this.errorMessage = <any>error
);
}
You will have all the details of IP in this.IppDetails
Upvotes: 1
Reputation: 57
You should try like this
var json = 'http://ipv4.myexternalip.com/json';
$http.get(json).then(function(result) {
console.log(result.data.ip)
}, function(e) {
alert("error");
});
Upvotes: 3